<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Address as AddressModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Car as CarModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 工程控制器
 * @package app\admin\controller
 */
class Order extends Admin
{
    /**
     * 工程列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $archives_sn = '';
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sn')$archives_sn = trim($v[2],'%');
            }
        }
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.create_time as contract_time')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->group('o.order_pid')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程管理（工程数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.sales', '销售经理', 'like'],
                //['daterange:2', 'o.contract_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['order_sn', '工程编号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch','批次数量'],
                ['client_id','销售经理',ClientModel::getSalesList()],
                /*['contract','合同','callback',function($value, $data){
                    if(empty($data['contract_time']))$value = '无';
                    else $value = '有';
                    return $value;
                },'__data__'],*/
                ['status_verify_uid','审核人',UserModel::getList()],
                //['back', '跟单人员'],
                //['contract_time', '合同签订日期','date'],
                ['money_str', '订金'],
                ['note', '收款方式','popover'],
                ['status','工程状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add') // 批量添加顶部按钮
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->addRightButton('archives',['title' => '查看所有批次','href' => url('mill/give/archives2',['order_pid' => '__order_pid__'])."?_s=archives_sn={$archives_sn}&_o=archives_sn=like",'class'=>'btn btn-default','icon'=>''])
            //->addRightButton('sample',['title' => '打印样品','href' => url('mill/sample/add',['order_id' => '__order_pid___']),'class'=>'btn btn-default','icon'=>''])
            //->addRightButton('contract',['title' => '打印合同','href' => url('mill/contract/add',['order_id' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->replaceRightButton(['status'=>['<>','1']],'','archives')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'order_sn'  => 150,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input();
            //自动生成工程编号
            //if(empty($data['order_sn']))$data['order_sn'] = OrderModel::orderSn();

            // 验证
            $result = $this->validate($data, 'Order');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            //判断工程号是否存在
            if(empty($re['id']) && !empty($re['order_sn'])){
                $order_sn = Db::name('mill_order')->where(['order_sn'=>$re['order_sn']])->value('order_sn');
                if(!empty($order_sn))$this->error('该工程号已存在');
            }

            //客户信息
            $client = ClientModel::get($data['client_id']);
            $data['nickname'] = $client['nickname'];
            $data['mobile'] = $client['mobile'];

            $data['create_time'] = empty($data['create_time'])?time():strtotime($data['create_time']);
            $data['update_time'] = time();
            $re = OrderModel::create($data);
            if ($re) {
                $id = $re['id'];
                OrderModel::update(['order_pid'=>$id],['id'=>$id]);
                $this->success('操作成功', url('index'));
            }
            $this->error('操作失败');
        }

        $info = [];
        //客户信息
        $client_id = input('client_id');
        $client = ClientModel::get($client_id);
        if(!empty($client['id'])){
            $info['client_id'] = $client['id'];
            $info['nickname'] = $client['nickname'];
            $info['mobile'] = $client['mobile'];
            $info['back'] = $client['back'];
        }
        //获取所有客户
        $client_list = ClientModel::getList('company');
        //获取所有客户对应跟单人员
        $back_list = ClientModel::getBackList();
        //js
        $js = '<script type="text/javascript">
                $(function(){
                    var vack_list = '.json_encode($back_list,JSON_UNESCAPED_UNICODE).';
                    $("#client_id").change(function(){
                    var client_id = $(this).children("option:selected").val();
                    //var nickname = $(this).children("option:selected").text();
                    $("#back").val(vack_list[client_id]);
                    //$("#nickname").val(nickname.split("--",1));
                    //$("#mobile").val(nickname.split("--")[1]);
                    })
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('新增客户工程') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'engineering', '工程名称'],
                ['text', 'order_sn', '工程编号'],
                ['hidden', 'nickname', '客户联系人'],
                ['hidden', 'mobile', '客户联系电话'],
                //['text', 'archives_sn', '档案号'],
                //['radio:||||must', 'money_str', '订金','',['未付'=>'未付','已付'=>'已付','无定金'=>'无定金'],'未付'],
                ['select:||||must', 'client_id', '选择客户[:请选择客户]', '', $client_list,''],
                ['text', 'back', '跟单人员'],
                //['file', 'contract', '合同'],
                //['text', 'batch', '批次'],
                //['date:||||must', 'create_time', '合同签订日期'],
                ['textarea', 'note', '备注'],
            ])
            ->setFormData($info)
            ->layout(['note'=>12])
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 编辑
     * @param null $id 客户id
     * @return mixed
     */
    public function edit($id=null)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Order');

            //验证工程号是否唯一
            $isOrder_sn = Db::name('mill_order')->where(['order_sn'=>$data['order_sn']])->value('order_pid');
            if(!empty($data['order_sn']) && !empty($isOrder_sn) && $isOrder_sn != $data['order_pid'])$this->error('该工程号已存在');

            //客户信息
            $client = ClientModel::get($data['client_id']);
            $data['nickname'] = $client['nickname'];
            $data['mobile'] = $client['mobile'];

            if(isset($data['status']) && $data['status'] == -1)$data['status'] = 0;
            if(isset($data['create_time']))$data['create_time'] = strtotime($data['create_time']);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            unset($data['order_pid']);
            // 更新数据
            if (OrderModel::update($data)) {
                //更新子工程数据
                $info = OrderModel::find($data['id']);
                unset($data['id']);
                unset($data['order_sn']);
                unset($data['archives_sn']);
                unset($data['batch']);
                unset($data['create_time']);
                unset($data['update_time']);
                OrderModel::update($data,['order_pid'=>$info['order_pid']]);

                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        $id = input('param.id');

        // 获取数据
        $info = OrderModel::find($id);
        //获取所有客户
        $client_list = ClientModel::getList('company');
        //获取所有客户对应跟单人员
        $back_list = ClientModel::getBackList();
        //js
        $js = '<script type="text/javascript">
                $(function(){
                    var vack_list = '.json_encode($back_list,JSON_UNESCAPED_UNICODE).';
                    $("#client_id").change(function(){
                    var client_id = $(this).children("option:selected").val();
                    //var nickname = $(this).children("option:selected").text();
                    $("#back").val(vack_list[client_id]);
                    //$("#nickname").val(nickname.split("--",1));
                    //$("#mobile").val(nickname.split("--")[1]);
                    })
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('编辑客户工程') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItem('hidden', 'order_pid')
            ->addFormItem('hidden', 'status')
            ->addFormItems([ // 批量添加表单项
                ['text', 'engineering', '工程名称'],
                ['text', 'order_sn', '工程编号'],
                ['hidden', 'nickname', '客户联系人'],
                ['hidden', 'mobile', '客户联系电话'],
                //['text', 'archives_sn', '档案号'],
                ['select:||||must', 'client_id', '选择客户[:请选择客户]', '', $client_list,''],
                ['text', 'back', '跟单人员'],
                //['file', 'contract', '合同'],
                //['text', 'batch', '批次'],
                //['date:||||must', 'create_time', '合同签订日期'],
                ['text', 'money_str', '订金'],
                ['textarea', 'note', '收款方式'],
            ])
            ->setFormData($info)
            //->layout(['note'=>12])
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 设置客户状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {

            switch ($type) {
                case 'enable':
                    if (false === OrderModel::where('id', $id)->setField('status', 1)) {
                        $this->error('审核失败，工程ID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === OrderModel::where('id', $id)->setField('status', -1)) {
                        $this->error('审核失败，工程ID：'.$id);
                    }
                    break;
                case 'delete':

                    if (false === OrderModel::where('id', 'in', $id)->delete()) {
                        $this->error('删除失败，工程ID：'.$id);
                    }
                    break;
                default:
                    $this->error('非法操作');
            }

            OrderModel::where('id', $id)->setField('status_verify_uid', UID);
            OrderModel::where('id', $id)->setField('status_time', time());

            action_log('role_'.$type, 'mill', $id, UID);
        }

        $this->success('操作成功');
    }
    /**
     * 待审核工程列表页
     * @return mixed
     */
    public function examine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        //$map[] = ['status','in','0,-1'];
        $map[] = $map0[] = $map01[] = ['archives_status','in','2'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate();
        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_order')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_order')->where($map01)->count();

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").text("面积表详情");
                    $(".archives_drawing").click(function(){
                        window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                    })
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('部门审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','callback',function($value, $data){
                    $value = Db::name('mill_client')->where(['id'=>$value])->value('company');

                    return $value;
                },'__data__'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['back_open', '设计内勤','text'],
                //['back_drawing','图纸','files'],
                ['archives_drawing','面积表','files.edit'],
                ['id','产品总数','callback',function($value, $data){
                    $archvices = ArchivesModel::getOneStat($value,'order_id');
                    return $archvices['number_sum'];
                },'__data__'],
                ['give_status','工程状态',GiveModel::$give_status],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addTopButtons('add,delete') // 批量添加顶部按钮
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->addRightButton('enable',['title' => '审核通过'])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('archives',['title' => '查看所有批次','href' => url('mill/give/archives',['archives_sn' => '__archives_sn__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('archivesShow',['title' => '面积表详情','href' => url('mill/give/archivesShow',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''])
            ->replaceRightButton(['status' => ['in', '1']], '', 'enable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
    /**
     * 上传图纸
     */
    public function drawing()
    {
        $id = input('param.id');
        $field = input('param.field');

        if ($this->request->isPost()) {

            $data = input();
            $id = input('param.id');
            if (false === OrderModel::where('id', $id)->setField($field, $data[$field])) {
                $this->error('上传失败');
            }

            $this->success('操作成功', null, '_parent_reload');
        }

        // 获取数据
        $info = OrderModel::find($id);
        $info['info_str'] = empty($info['archives_sn'])?'无档案号':$info['archives_sn'];
        $info['info_str'] = "档案号|{$info['info_str']}——客户公司|{$info['company']}——工程名称|{$info['engineering']}";

        return ZBuilder::make('form')
            ->setPageTitle('上传图纸') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['static:12', 'info_str', ''],
                ['file:12', $field, '请上传图纸'],
            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 审核
     */
    public function backEnable()
    {

        $ids = input('ids');
        $id = input('id');
        if($id)$ids[] = $id;
        if(empty($ids))$this->error('请选择工程');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);

        foreach ($ids as $id){
            if (false === OrderModel::where('id', $id)->setField($fieldv[0], $fieldv[1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            //审核人员
            OrderModel::where('id', $id)->setField($fieldv[0].'_verify_uid', UID);
            //审核时间
            OrderModel::where('id', $id)->setField($fieldv[0].'_time', time());
        }


        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === OrderModel::where('id', $id)->setField($field, -1)) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))OrderModel::where('id', $id)->setField($field.'_note', $data[$field.'_note']);
            //审核人员
            OrderModel::where('id', $id)->setField($field.'_verify_uid', UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }
    /**
     * 标签打印列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPrintList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        //$map[] = ['o.status','=',1];
        $map[] = ['o.archives_status','=',2];
        $archives_sn = '';
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sn')$archives_sn = trim($v[2],'%');
            }
        }
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.create_time as contract_time')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            //->group('o.order_pid')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('标签打印（工程数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.print_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch','批次数量'],
                ['status_verify_uid','审核人',UserModel::getList()],
                ['note', '备注','popover'],
                ['archives_status','面积表审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$archives_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['archives_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            //->addRightButton('archives',['title' => '查看所有批次','href' => url('mill/give/archives2',['order_pid' => '__order_pid__'])."?_s=archives_sn={$archives_sn}&_o=archives_sn=like",'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('archivesGive',['title' => '查看详情','href' => url('mill/give/archivesGive2',['id' => '__id__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 计划单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function plan(){

        $give_status = input('give_status');

        if ($this->request->isPost()){

            $start_time = input('start_time');
            if(empty($start_time))$this->error("请选择计划日期");
            $start_time = strtotime($start_time);
            $end_time = strtotime(date('Y-m-d 23:59:59',$start_time));

            $archives_sn = input('archives_sn');
            $archives_sn = str_replace("，",",",$archives_sn);
            $archives_sn = explode(',',$archives_sn);

            foreach ($archives_sn as $v){
                if(empty($v))$this->error("请输入正确的档案号[{$v}]");

                $where = [
                    ['archives_sn','=',$v],
                ];
                $order = Db::name('mill_order')
                    ->where($where)
                    ->find();

                if(empty($order))$this->error("该订单不存在[{$v}]");

                $where = [
                    ['order_id','=',$order['id']],
                ];
                $plan = Db::name('mill_order_plan')
                    ->where($where)
                    ->where("(start_time between {$start_time} and {$end_time}) or (end_time between {$start_time} and {$end_time}) ")
                    ->find();

                if(!empty($plan)){
                    if($plan['delete'] == 1)$this->error("该订单[{$v}]已排期[".date('Y-m-d',$plan['start_time'])."至".date('Y-m-d',$plan['end_time'])."]");
                    Db::name('mill_order_plan')->delete(['id'=>$plan['id']]);
                }

            }

            foreach ($archives_sn as $v){

                $where = [
                    ['archives_sn','=',$v],
                ];
                $order = Db::name('mill_order')
                    ->where($where)
                    ->find();

                //同步同产品的发货信息
                $update = [
                    'order_id'          =>  $order['id'],
                    'archives_sn'       =>  $order['archives_sn'],
                    'give_status'       =>  $give_status,
                    'start_time'        =>  $start_time,
                    'end_time'          =>  $end_time,
                    'create_time'       =>  time(),
                ];

                if(!(Db::name('mill_order_plan')->insert($update))){
                    $this->error('操作失败');
                }
            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('计划单') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'archives_sn','档案号'],
                ['date:||||must', 'start_time', '计划日期'],
            ])
            ->layout(['archives_sn'=>12,'start_time'=>12])
            ->fetch();

    }
    /**
     * 删除计划单
     */
    public function planDel()
    {
        $order_id = input('order_id');
        $archives_sn = input('archives_sn');
        $give_status = input('give_status');
        $starttime = strtotime(input('starttime'));
        $endtime = strtotime(input('endtime'));
        $endtime = strtotime(date("Y-m-d 23:59:59", $endtime));

        //时间差
        $day_time = intval(($endtime+1-$starttime)/86400);

        $where = [
            ['order_id','=',$order_id],
            ['give_status','=',$give_status],
        ];

        while (1 <= $day_time) {
            $new_date = strtotime(date('Y-m-d', strtotime("-{$day_time} day",($endtime + 1))));
            $end_date = strtotime(date('Y-m-d H:i:s',strtotime("+1 day",$new_date)-1));

            $plan = Db::name('mill_order_plan')
                ->where($where)
                ->where("(start_time between {$new_date} and {$end_date}) or (end_time between {$new_date} and {$end_date}) ")
                ->find();

            if(!empty($plan))Db::name('mill_order_plan')->where(['id'=>$plan['id']])->update(['delete'=>0]);
            else{
                //同步同产品的发货信息
                $update = [
                    'order_id'          =>  $order_id,
                    'archives_sn'       =>  $archives_sn,
                    'give_status'       =>  $give_status,
                    'start_time'        =>  $new_date,
                    'end_time'          =>  $end_date,
                    'delete'            =>  0,
                    'create_time'       =>  time(),
                ];

                if(!(Db::name('mill_order_plan')->insert($update))){
                    $this->error('操作失败');
                }
            }

            --$day_time;
        }

        $this->success('操作成功');

    }

    //---------------------------------------合同管理----------------------------------------------------
    /**
     * 待审核外勤列表页
     * @return mixed
     */
    public function waiBack()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        //$map0[] = $map01[] = $map[] = ['status','eq','1'];
        //$map[] = ['waiback_status','in','0,-1'];

        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate()
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".drawing_btn").css("display","none");
                    $(".waiback_drawing").click(function(){
                        $(this).parents("tr").find("[data-files='."'".'drawing'."'".']").click();
                    })
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计外勤') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['waiback_open', '设计外勤','text.edit'],
                ['waiback_status_time', '日期','date',date('Y-m-d')],
                //['waiback_drawing','图纸','files.edit'],
                /*['waiback_status','设计外勤审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$waiback_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['waiback_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addRightButton('backEnable',['title' => '接单','href' => url('backEnable',['id' => '__id__']).'?fieldv=waiback_status|2','class'=>'btn btn-default disable-dch ajax-get','icon'=>''])
            ->addRightButton('drawing',['title' => '选择图纸','href' => url('drawing',['id' => '__id__','field'=>'waiback_drawing']),'icon'=>'','class'=>'btn btn-default disable-dch drawing_btn','data-files'=>'drawing'],['area' => ['780px', '50%'], 'title' => ['选择图纸', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['waiback_status_time'=>['>',0]],'<a title="" icon="" class="btn btn-default disable-dch drawing_btn pop" href="'.url('drawing',['id' => '__id__','field'=>'waiback_drawing']).'" data-files="drawing" data-layer="{&quot;area&quot;:[&quot;780px&quot;,&quot;50%&quot;],&quot;title&quot;:[&quot;\u9009\u62e9\u56fe\u7eb8&quot;,&quot;font-size:24px;text-align: center;&quot;]}" _tag="drawing" data-toggle="tooltip" data-original-title="选择图纸" style="display: none;"><i class=""></i>选择图纸</a>')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 待审核外勤列表页
     * @return mixed
     */
    public function waiBackVerify()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map0[] = $map01[] = $map[] = ['status','eq','1'];
        $map[] = ['waiback_status','in','1,-1'];

        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate()
        ;
        //待审核
        $map0[] = ['waiback_status','eq','1'];
        $total0 = Db::name('mill_order')->where($map0)->count();
        //未通过
        $map01[] = ['waiback_status','eq','-1'];
        $total01 = Db::name('mill_order')->where($map01)->count();

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".waiback_status").click(function(){
                        $(this).parents("tr").find("[data-files='."'".'drawing'."'".']").click();
                    })
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计外勤（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['waiback_open', '设计外勤'],
                ['waiback_drawing','图纸','files'],
                ['waiback_status','设计外勤审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$waiback_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['waiback_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addRightButton('edit')
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__']).'?fieldv=waiback_status|2','class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'waiback_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    //---------------------------------------样品管理----------------------------------------------------
    /**
     * 待提交内勤列表页
     * @return mixed
     */
    public function back()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map0[] = $map01[] = $map[] = ['waiback_status','eq','2'];
        //$map[] = ['back_status','in','0,-1'];

        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate()
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".drawing_btn").css("display","none");
                    $(".back_drawing").click(function(){
                        $(this).parents("tr").find("[data-files='."'".'drawing'."'".']").click();
                    })
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计内勤') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['back_open', '设计内勤','text.edit'],
                ['back_status_time', '日期','date',date('Y-m-d')],
                //['back_drawing','图纸','files.edit'],
                /*['back_status','设计内勤审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$back_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['back_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addRightButton('backEnable',['title' => '接单','href' => url('backEnable',['id' => '__id__']).'?fieldv=back_status|2','class'=>'btn btn-default disable-dch ajax-get','icon'=>''])
            ->addRightButton('drawing',['title' => '选择图纸','href' => url('drawing',['id' => '__id__','field'=>'back_drawing']),'icon'=>'','class'=>'btn btn-default drawing_btn','data-files'=>'drawing'],['area' => ['780px', '50%'], 'title' => ['选择图纸', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['back_status_time'=>['>',0]],'<a title="" icon="" class="btn btn-default disable-dch drawing_btn pop" href="'.url('drawing',['id' => '__id__','field'=>'back_drawing']).'" data-files="drawing" data-layer="{&quot;area&quot;:[&quot;780px&quot;,&quot;50%&quot;],&quot;title&quot;:[&quot;\u9009\u62e9\u56fe\u7eb8&quot;,&quot;font-size:24px;text-align: center;&quot;]}" _tag="drawing" data-toggle="tooltip" data-original-title="选择图纸" style="display: none;"><i class=""></i>选择图纸</a>')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 待审核内勤列表页
     * @return mixed
     */
    public function backVerify()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map0[] = $map01[] = $map[] = ['waiback_status','eq','2'];
        $map[] = ['back_status','in','1,-1'];

        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate()
        ;
        //待审核
        $map0[] = ['back_status','eq','1'];
        $total0 = Db::name('mill_order')->where($map0)->count();
        //未通过
        $map01[] = ['back_status','eq','-1'];
        $total01 = Db::name('mill_order')->where($map01)->count();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计内勤（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['back_open', '设计内勤','text.edit'],
                ['back_drawing','图纸','files'],
                ['back_status','设计内勤审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$back_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['back_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['note','备注'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('edit')
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__']).'?fieldv=back_status|2','class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'back_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    //---------------------------------------面积部----------------------------------------------------
    /**
     * 待上传面积列表页
     * @return mixed
     */
    public function archives()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map0[] = $map01[] = $map[] = ['back_status','eq','2'];
        $map[] = ['archives_status','in','0,-1,2'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2,id as id2')
            ->where($map)
            ->order('archives_status asc,archives_status_time desc,id desc')
            ->paginate()
            ->each(function ($v){
                //$archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                //$v = array_merge($v,$archvices);
                $v['area_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('one_area*number');
                $v['number_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('number');
                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").click(function(){
                        //window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                        var href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                        swal({
                            title: "确定要修改面积表吗？",
                            text: "",
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#d26a5c",
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            closeOnConfirm: true,
                            html: false
                        }, function () {
                            window.location.href = href;
                        });
                    })
                });
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('上传面积表') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['select:2', 'archives_status', '面积表审核','','',OrderModel::$archives_status],
                ['text:2', 'order_sn', '工程编号', 'like'],
                ['select:2', 'client_id', '客户公司','','',$company],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'archives_status_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['archives_status_time', '工程日期','date'],
                ['order_sn', '工程编号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum','产品总量'],
                ['area_sum','总面积'],
                //['back_open', '设计内勤','text'],
                //['waiback_open', '设计外勤','text'],
                //['back_drawing','图纸','files'],
                ['archives_drawing','面积表','files.edit'],
                ['archives_status_time','上传日期','date'],
                ['status','工程状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['archives_status','面积表审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$archives_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['archives_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['id2','打印状态','callback',function($value){
                    $status = Db::name('mill_order_archives_give')->where(['order_id'=>$value])->order('quality_repair asc')->value('quality_repair');
                    $status = intval($status);
                    $status = OrderModel::status_tag($status,GiveModel::$quality_repair[$status]);
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addRightButton('backEnable',['title' => '提交审核','href' => url('archivesEnable',['id' => '__id__']).'?fieldv=archives_status|1','class'=>'btn btn-default disable-dch ajax-get','icon'=>''])
            ->addRightButton('delEnable',['title' => '申请删除','href' => url('archivesEnable',['id' => '__id__']).'?fieldv=archives_del_status|1','class'=>'btn btn-default disable-dch ajax-get','icon'=>''])
            ->addRightButton('archivesEdit',['title' => '上传面积表','href' => url('archivesEdit',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''])
            ->addRightButton('delArchives',['title' => '删除','href' => url('delArchives',['order_id'=>'__id__']),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])
            //->addRightButton('archivesGive',['title' => '打印(不带LOGO)','href' => url('mill/give/archivesgive2',['id' => '__id__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            //->addRightButton('archivesGive',['title' => '打印(带LOGO)','href' => url('mill/give/archivesgive2',['id' => '__id__','watermark'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('addArchives',['title' => '新增','href' => url('archivesEdit',['order_pid' => '__order_pid__']),'class'=>'btn btn-primary disable-dch','icon'=>''])
            //->addRightButton('archivesList',['title' => '编辑面积表','href' => url('mill/order/archivesList',['order_id' => '__id__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->replaceRightButton(['archives_status' => ['=','2']],'',['backEnable'])
            ->replaceRightButton(['archives_status' => ['=','0']],'',['delEnable'])
            ->replaceRightButton(['archives_del_status' => ['in','1,2']],'',['delEnable'])
            ->replaceRightButton(['archives_del_status' => ['<>','2']],'',['delArchives'])
            ->replaceRightButton(['give_status' => ['<>','0']],'',['delEnable'])
            ->replaceRightButton(['archives_status' => ['<>','2']],'',['archivesGive','addArchives','archivesList'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'order_sn'  => 150,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 提交审核
     */
    public function archivesEnable(){
        return $this->backEnable();
    }
    /**
     * 待审核上传面积表列表页
     * @return mixed
     */
    public function archivesVerify($archives_status = '1')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map0[] = $map01[] = $map[] = ['back_status','eq','2'];
        $map[] = ['archives_status','in',$archives_status];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate()
            ->each(function ($v){
                $v['area_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('one_area*number');
                $v['number_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('number');
                return $v;
            })
        ;
        //待审核
        $map0[] = ['archives_status','eq','1'];
        $total0 = Db::name('mill_order')->where($map0)->count();
        //未通过
        $map01[] = ['archives_status','eq','-1'];
        $total01 = Db::name('mill_order')->where($map01)->count();

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").text("面积表详情");
                    $(".archives_drawing").click(function(){
                        window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                    })
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('面积表审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['back_open', '设计内勤','text'],
                //['back_drawing','图纸','files'],
                ['number_sum','产品总量'],
                ['area_sum', '总面积'],
                ['archives_drawing','面积表','files.edit'],
                ['archives_status','面积表审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$archives_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['archives_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addTopButton('backEnable',['title' => '审核通过','href' => url('backEnable').'?fieldv=archives_status|2','class'=>'btn btn-primary confirm ajax-post','icon'=>'','target-form'=>'ids'])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__']).'?fieldv=archives_status|2','class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'archives_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesShow',['title' => '面积表详情','href' => url('archivesShow',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 待审核面积表申请删除列表页
     * @return mixed
     */
    public function archivesDelVerify($archives_status = '1')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map0[] = $map01[] = $map[] = ['back_status','eq','2'];
        $map[] = ['archives_del_status','in',$archives_status];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('id desc')
            ->paginate()
            ->each(function ($v){
                $v['area_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('one_area*number');
                $v['number_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('number');
                return $v;
            })
        ;
        //待审核
        $map0[] = ['archives_del_status','eq','1'];
        $total0 = Db::name('mill_order')->where($map0)->count();
        //未通过
        $map01[] = ['archives_del_status','eq','-1'];
        $total01 = Db::name('mill_order')->where($map01)->count();

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").text("面积表详情");
                    $(".archives_drawing").click(function(){
                        window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                    })
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('面积表删除审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['back', '内勤(销售)'],
                //['back_open', '设计内勤','text'],
                //['back_drawing','图纸','files'],
                ['number_sum','产品总量'],
                ['area_sum', '总面积'],
                ['archives_drawing','面积表','files.edit'],
                ['archives_del_status','面积表审核','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$archives_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['archives_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__']).'?fieldv=archives_del_status|2','class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'archives_del_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesShow2',['title' => '面积表详情','href' => url('archivesShow2',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 未通过审核上传面积表列表页
     * @return mixed
     */
    public function archivesVerifyNo(){
        return $this->archivesVerify('-1');
    }
    /**
     * 获取面积表文档信息并编译
     */
    public function archivesDrawing_old()
    {

        // 接收附件 ID
        $id = input('param.id');
        // 获取附件 ID 完整路径
        $file = get_file_path($id);
        //$full_path = 'D:/office/phpstudy_pro/WWW/xxy/public/uploads/files/20210611/49dc8272891a2dbdc3396fc055d8017c.xls';
        if(strpos(getcwd(),'public') && strpos($file,'public'))$file = explode('public',$file)[1];
        $full_path = getcwd() . $file;

        $head_table = [
            'sheet'         =>  '输入表',
            'rowStart'      =>  2,
            'rowEnd'        =>  2,
            'table'         =>  'order',
            'fields'        =>  [
                'D-3'       =>  'engineering',
                //'C-3'       =>  'archives_open',
                'S-2'       =>  'archives_handle',
                //'R-4'       =>  'archives_version',
                'L-4'       =>  'archives_sign_time',
                //'G-2'       =>  'archives_bill_time',
                //'I-2'       =>  'order_sn',
                //'N-2'       =>  'engineering_full',
                'H-3'       =>  'batch',
            ]
        ];
        $archives_table = [
            'sheet'         =>  '面积清单',
            'rowStart'      =>  8,
            //'rowEnd'        =>  5,
            'table'         =>  'order_archives',
            'fields'        =>  [
                'A'         =>  'sort',
                'B'         =>  'page',
                'C'         =>  'model_sn',
                'D'         =>  'thickness',
                'E'         =>  'long',
                'F'         =>  'high',
                'G'         =>  'one_area',
                'H'         =>  'number',
                'I'         =>  'row_area',
                'J'         =>  'color',
                'K'         =>  'model',
                'L'         =>  'torque',
                'M'         =>  'slot',
                'N'         =>  'weld',
                //'Q'         =>  'plank',
            ],
            'group'         =>  [
                'fields'    =>  ['thickness','color','model'],
                'sum'       =>  ['number','row_area']
            ]
        ];
        $sheet_read_arr = [$head_table,$archives_table];
        $import = plugin_action('Excel/Excel/importarchives', [$full_path,$sheet_read_arr]);

        echo json_encode($import,JSON_UNESCAPED_UNICODE);exit;

    }
    /**
     * 编辑面积表
     * @param null $id 工程id
     * @param bool $isEdit 是否可编辑
     * @return mixed
     */
    public function archivesEdit_old($id=null,$isEdit=true)
    {

        if ($this->request->isPost() && $isEdit) {
            $data = $this->request->post();
            //是否为新增面积表，是新增面积表，则自动新增工程
            $is_pid = $data['is_pid'];
            $archives_lists = isset($data['archives_lists'])?$data['archives_lists']:'';
            unset($data['archives_lists']);
            unset($data['is_pid']);
            // 验证
            $result = $this->validate($data, 'Order');
            //if(empty($data['archives_drawing']))$this->error('请上传面积表');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            //不需要审核，默认审核通过
            $data['archives_status'] = 2;
            $data['archives_status_time'] = time();
            $data['status'] = 1;
            $data['status_time'] = time();

            //自动生成档案编号
            $batch_str = '';
            if(strpos($data['batch'], '补'))$batch_str = 'B';
            if(strpos($data['batch'], '改'))$batch_str = 'G';
            if(empty($data['order_sn']))$data['order_sn'] = Db::name('mill_order')->where(['id'=>$data['order_pid']])->value('order_sn');
            //$data['archives_sn'] = "{$data['order_sn']}-".findNum($data['batch']).$batch_str;
            $data['archives_sn'] = "{$data['order_sn']}-{$data['batch']}";

            //验证档案号是否唯一
            $isArchives_sn = Db::name('mill_order')->where(['archives_sn'=>$data['archives_sn']])->value('id');

            if($is_pid){
                $order_sn = Db::name('mill_order')->where(['id'=>$data['order_pid']])->value('order_sn');
                if($isArchives_sn)$this->error('该批次已存在');
                if($order_sn != $data['order_sn'])$this->error('工程号不匹配');

                unset($data['id']);

                $data['archives_bill_time'] = time();
                $data['archives_sign_time'] = time();

                $re = OrderModel::create($data);
                if(!empty($re['id']))$id = $re['id'];
            }
            else {
                $info = Db::name('mill_order')->where(['id'=>$data['id']])->find();
                if(!empty($isArchives_sn) && $isArchives_sn != $data['id'])$this->error('该批次已存在');
                if(!empty($info['order_sn']) && $info['order_sn'] != $data['order_sn'])$this->error('工程号不匹配');
                if(empty($info['archives_bill_time']))$data['archives_bill_time'] = time();
                if(empty($info['archives_sign_time']))$data['archives_sign_time'] = time();

                $is_speed = Db::name('mill_order_archives_give')->where([['order_id','=',$id],['status','<>',0]])->count();

                $re = OrderModel::update($data);
            }
            // 更新数据
            if ($re) {

                //更新面积表
                if(!empty($archives_lists)){
                    //if(empty($archives_lists[0]['sort']))$this->error('请上传序号');
                    //未投入生产的直接重新录入
                    if(empty($is_speed) && 1==2){//暂时作废
                        Db::name('mill_order_archives')->where('order_id='.$id)->delete();//删除已存在的数据
                        Db::name('mill_order_archives_give')->where('order_id='.$id)->delete();//删除已存在的数据

                        Db::name('mill_order_archives')->insertAll($archives_lists);//重新批量录入
                    }
                    //已投入生产的则循环遍历更新
                    else{
                        //获取所有面积表序列
                        $sort_list = Db::name('mill_order_archives')->where(['order_id'=>$id])->order('sort asc')->column('sort');
                        if(!empty($sort_list))$sort_list = array_flip($sort_list);
                        //获取最后一件产品的序列
                        $sort = Db::name('mill_order_archives_give')
                            ->where(['order_id'=>$id])
                            ->order('sort desc')
                            ->value('sort');

                        foreach ($archives_lists as $av){
                            //过滤未被删减的面积表序列
                            if(!empty($sort_list))unset($sort_list[$av['sort']]);

                            $extra = empty($av['extra'])?'':$av['extra'];
                            //录入配件产品
                            if($extra == 1 && 1==2){
                                $archives_where = [
                                    'order_id'  =>  $id,
                                    'sort'  =>  $av['sort'],
                                ];
                                $archives = Db::name('mill_order_archives_extra')->where($archives_where)->find();

                                //录入
                                if(empty($archives)) Db::name('mill_order_archives_extra')->insert($av);
                                //更新
                                else Db::name('mill_order_archives_extra')->where(['id'=>$archives['id']])->update($av);
                                //跳过本次循环
                                continue;
                            }
                            $archives_where = [
                                'order_id'  =>  $id,
                                'sort'  =>  $av['sort'],
                            ];
                            $archives = Db::name('mill_order_archives')->where($archives_where)->find();
                            //录入
                            if(empty($archives)) {
                                $archives['id'] = Db::name('mill_order_archives')->insertGetId($av);
                                //后续新增的面积表序列，且有已被投入生产的产品，则插入新增的产品
                                if($sort){
                                    $archives = Db::name('mill_order_archives')->where($archives_where)->find();
                                    //获取最后一件产品
                                    $give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                                    $count_x = $av['number'];
                                    if(!empty($give)){

                                        //获取该序列最后一件产品的序号
                                        $counter_last = Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->order('sort desc')->value('counter');
                                        $counter_last = intval($counter_last);
                                        for($i=($counter_last+1);$i<=($counter_last+$count_x);$i++){
                                            $counter = $i;//计件数
                                            $sort++;//计件数+1
                                            $add = [
                                                'order_id'              =>  $archives['order_id'],
                                                'order_pid'             =>  $archives['order_pid'],
                                                'archives_id'           =>  $archives['id'],
                                                'archives_sn'           =>  $archives['archives_sn'],
                                                'counter'               =>  $counter,
                                                'give_date'             =>  $give['give_date'],
                                                'batch'                 =>  $give['batch'],
                                                'sort'                  =>  $sort,
                                                'give_sn'               =>  GiveModel::giveSn($give['give_date'],$give['batch'],$sort),
                                            ];

                                            Db::name('mill_order_archives_give')->insert($add);
                                        }
                                    }
                                }

                            }
                            //更新
                            else{
                                //有产品增加
                                if($av['number'] > $archives['number']){
                                    //获取最后一件产品
                                    $give_where = [
                                        'archives_id'   =>  $archives['id'],
                                    ];
                                    $give = Db::name('mill_order_archives_give')->where($give_where)->order('counter desc')->find();
                                    if(empty($give)){
                                        $give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                                        $archives['number'] = 0;
                                    }
                                    $count_x = $av['number']-$archives['number'];
                                    if(!empty($give)){

                                        //获取该序列最后一件产品的序号
                                        $counter_last = Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->order('sort desc')->value('counter');
                                        $counter_last = intval($counter_last);
                                        for($i=($counter_last+1);$i<=($counter_last+$count_x);$i++){
                                            $counter = $i;//计件数
                                            $sort++;//计件数+1
                                            $add = [
                                                'order_id'              =>  $archives['order_id'],
                                                'order_pid'             =>  $archives['order_pid'],
                                                'archives_id'           =>  $archives['id'],
                                                'archives_sn'           =>  $archives['archives_sn'],
                                                'counter'               =>  $counter,
                                                'give_date'             =>  $give['give_date'],
                                                'batch'                 =>  $give['batch'],
                                                'sort'                  =>  $sort,
                                                'give_sn'               =>  GiveModel::giveSn($give['give_date'],$give['batch'],$sort),
                                            ];

                                            Db::name('mill_order_archives_give')->insert($add);
                                        }
                                    }
                                }
                                //有产品减少
                                elseif($av['number'] < $archives['number']){
                                    //获取最初始状态的产品
                                    $give_where = [
                                        ['archives_id','=',$archives['id']],
                                        ['quality_status','>=','-1'],
                                    ];
                                    $count_x = $archives['number']-$av['number'];
                                    $give_id = Db::name('mill_order_archives_give')
                                        ->where($give_where)
                                        ->order('status asc,sort desc')
                                        ->limit($count_x)
                                        ->column('id');
                                    $give_update_x = ['quality_status'=>'-3',];
                                    if(!empty($give_id)){
                                        $give_id = implode(',',$give_id);
                                        Db::name('mill_order_archives_give')->where([['id','in',$give_id]])->update($give_update_x);
                                    }
                                }
                                //更新
                                Db::name('mill_order_archives')->where(['id'=>$archives['id']])->update($av);
                            }
                        }
                        //清除删减的面积表序列
                        if(!empty($sort_list)){
                            $sort_list = array_keys($sort_list);
                            $sort_ids = Db::name('mill_order_archives')->where([['order_id','=',$id],['sort','in',implode(',',$sort_list)]])->order('sort asc')->column('id');
                            if(!empty($sort_ids)){
                                $sort_ids = implode(',',$sort_ids);
                                Db::name('mill_order_archives')->where("id in ({$sort_ids})")->delete();//删除已存在的数据
                                Db::name('mill_order_archives_give')->where("archives_id in ({$sort_ids})")->delete();//删除已存在的数据
                            }
                            //配件
                            $sort_ids_extra = Db::name('mill_order_archives_extra')->where([['order_id','=',$id],['sort','in',implode(',',$sort_list)]])->order('sort asc')->column('id');
                            if(!empty($sort_ids_extra)){
                                $sort_ids_extra = implode(',',$sort_ids_extra);
                                Db::name('mill_order_archives_extra')->where("id in ({$sort_ids_extra})")->delete();//删除已存在的数据
                            }
                        }
                    }

                    if($is_pid && cookie('__encry__')){
                        Db::name('mill_order_archives')->where(['encry'=>cookie('__encry__')])->update(['order_id'=>$id,'encry'=>'']);
                        cookie('__encry__','');
                    }
                }
                //更新档案号
                Db::name('mill_order_archives')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);
                Db::name('mill_order_archives_give')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);
                Db::name('mill_order_archives_extra')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);

                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        $id = input('param.id');
        $order_pid = input('param.order_pid');
        if(empty($id) && empty($order_pid))$this->error('错误操作');
        $is_pid = false;
        $encry = '';//加密串
        // 获取数据
        if($id)$info = OrderModel::find($id);
        elseif ($order_pid){
            $info = OrderModel::where(['order_pid'=>$order_pid])->find();
            $is_pid = true;
            //生成加密串
            $encry = Auth::token();
            cookie('__encry__', $encry);

            unset($info['archives_drawing']);
            unset($info['archives_bill_time']);
            unset($info['archives_sign_time']);
            unset($info['batch']);
            unset($info['archives_handle']);
            unset($info['archives_open']);
            unset($info['archives_plan']);
            unset($info['archives_sn']);
            //unset($info['order_sn']);
            unset($info['order_sn_off']);
            unset($info['archives_version']);
            unset($info['archives_type']);
            unset($info['give_status']);
            unset($info['give_pro']);
            unset($info['archives_del_status']);
            unset($info['archives_del_status_verify_uid']);
            unset($info['archives_del_status_time']);
            unset($info['archives_del_status_note']);
            unset($info['urgent_status']);
            unset($info['urgent_status_time']);
        }
        $info['is_pid'] = $is_pid;
        $info['archives_drawing'] = empty($info['archives_drawing'])?'':$info['archives_drawing'];
        $info['archives_bill_time'] = empty($info['archives_bill_time'])?'':$info['archives_bill_time'];
        $info['archives_sign_time'] = empty($info['archives_sign_time'])?'':$info['archives_sign_time'];
        //js
        $js = '<script type="text/javascript">
                //上传面积表成功后的回调
                var dp_file_upload_success_archives_drawing = function () {
                    //面积表文档ID
                    var archives_drawing = $("input[name=archives_drawing]").val();
                    //获取面积表文档信息并编译
                    $.ajax({
                        url: \''.url("archivesDrawing").'?id=\'+archives_drawing,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        
                        //更新工程信息
                        var order = [];
                        if(data.order.lists[0]){
                            order = data.order.lists[0];
                            //---------去掉档案号里的批次 start---------------
                            //var order_sn_arr = order.order_sn.split("-");
                            //order.order_sn = "";
                            //for (var i = 0; i < (order_sn_arr.length-1); ++i) {
                            //    order.order_sn += "-"+order_sn_arr[i];
                            //}
                            //order.order_sn = order.order_sn.replace(/(^-)|(-$)/g,\'\');
                            //---------去掉档案号里的批次 end------------------
                            
                            //order.archives_sn = order.order_sn+"-"+order.batch;
                            //$("input[name=engineering]").val(order.engineering);
                            //$("input[name=order_sn]").val(order.order_sn);
                            //$("input[name=order_sn_off]").val(order.order_sn_off);
                            //$("input[name=archives_version]").val(order.archives_version);
                            //$("input[name=archives_sn]").val(order.archives_sn);
                            //$("input[name=archives_bill_time]").val(order.archives_bill_time);
                            //$("input[name=archives_sign_time]").val(order.archives_sign_time);
                            //$("input[name=archives_open]").val(order.archives_open);
                            $("input[name=batch]").val(order.batch);
                        }
                        
                        //更新面积表信息
                        var archives_html = "";
                        if(data.order_archives.lists){
                            var lists = data.order_archives.lists;
                            
                            //序号
                            var sort_arr = [];
                            //铝板编号
                            var model_sn_arr = [];
                            //配件统计
                            var archives_extra_html = "";
                            //新增面积表时，判断序号是否连号
                            //var archives_drawing = "'.$info['archives_drawing'].'";//是否为新增
                            var sort_i = 1;//序号连号计数器
                            var number_sum = 0;
                            var row_area_sum = 0;
                            $.each(lists,function(i,v){
                                if(!v.hasOwnProperty("torque"))v["torque"] = "";
                                if(!v.hasOwnProperty("bend"))v["bend"] = "";
                                if(!v.hasOwnProperty("extra"))v["extra"] = "";
                                if(!v.hasOwnProperty("stiffener"))v["stiffener"] = "";
                                if(!v.hasOwnProperty("note"))v["note"] = "";
                                
                                var model_sn = v["model_sn"];
                                //判断铝板编号是否重复
                                if(model_sn_arr.includes(model_sn)){
                                    //Dolphin.notify("铝板编号【"+model_sn+"】有重复", "danger");
                                }
                                model_sn_arr.push(model_sn);
                                var k = v["sort"];
                                if(k == ""||k == "null"){
                                    Dolphin.notify("序号不能为空", "danger");
                                }
                                //判断序号是否重复
                                if(sort_arr.includes(k)){
                                    Dolphin.notify("序号【"+k+"】有重复", "danger");
                                }
                                sort_arr.push(k);
                                //判断序号是否连号
                                //if((archives_drawing == ""||archives_drawing == "null")&&(sort_i!=k)){
                                if(sort_i!=k){
                                    //Dolphin.notify("序号["+k+"]不连号", "danger");
                                }
                                v["row_area"] = Math.round((v["number"]*v["one_area"])*1000000)/1000000;
                                archives_html += "<tr><input type=\'hidden\' name=\'archives_lists["+k+"][order_id]\' value=\''.$id.'\'><input type=\'hidden\' name=\'archives_lists["+k+"][order_pid]\' value=\''.$info['order_pid'].'\'><input type=\'hidden\' name=\'archives_lists["+k+"][encry]\' value=\''.$encry.'\'><input type=\'hidden\' name=\'archives_lists["+k+"][slot]\' value=\'"+v["slot"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][weld]\' value=\'"+v["weld"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][torque]\' value=\'"+v["torque"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][bend]\' value=\'"+v["bend"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][corner]\' value=\'"+v["corner"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][tube]\' value=\'"+v["tube"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][expaint]\' value=\'"+v["expaint"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][extra]\' value=\'"+v["extra"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][stiffener]\' value=\'"+v["stiffener"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][note]\' value=\'"+v["note"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][archives_sn]\' value=\'"+order.archives_sn+"\'>"
                                +"<td>"+v["sort"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][sort]\' value=\'"+v["sort"]+"\'></td>"
                                +"<td>"+v["page"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][page]\' value=\'"+v["page"]+"\'></td>"
                                +"<td>"+v["model_sn"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][model_sn]\' value=\'"+v["model_sn"]+"\'></td>"
                                +"<td>"+v["thickness"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][thickness]\' value=\'"+v["thickness"]+"\'></td>"
                                +"<td>"+v["long"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][long]\' value=\'"+v["long"]+"\'></td>"
                                +"<td>"+v["high"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][high]\' value=\'"+v["high"]+"\'></td>"
                                +"<td>"+v["one_area"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][one_area]\' value=\'"+v["one_area"]+"\'></td>"
                                +"<td>"+v["number"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][number]\' value=\'"+v["number"]+"\'></td>"
                                +"<td>"+v["row_area"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][row_area]\' value=\'"+v["row_area"]+"\'></td>"
                                +"<td>"+v["color"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][color]\' value=\'"+v["color"]+"\'></td>"
                                +"<td>"+v["model"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][model]\' value=\'"+v["model"]+"\'></td>"
                                +"</tr>";
                                
                                //配件组装
                                if(v["extra"] == 1){
                                    archives_extra_html += "<tr>"
                                    +"<td>"+v["model_sn"]+"</td>"
                                    +"<td>"+v["number"]+"</td>"
                                    +"</tr>";
                                }
                                
                                number_sum += parseFloat(v["number"]);
                                row_area_sum += parseFloat(v["row_area"]);
                                sort_i ++;
                            });
                            
                            //组装
                            archives_html += "<tr><td colspan=\'13\' style=\'text-align: right;\'>合计数量：<a style=\'font-size: 25px;\'>"+number_sum+"</a>  合计面积(M²)：<a style=\'font-size: 25px;\'>"+Math.round(row_area_sum*1000000)/1000000+"</a></td></tr>";
                            $("#table-list_archives").find("tbody").html(archives_html);
                        }
                        
                        //配件统计
                        $("#table-list_archives_extra").find("tbody").html(archives_extra_html);
                        
                        //更新统计信息
                        var archives_group_html = "";
                        var archives_color_obj = {};//颜色统计
                        if(data.order_archives.group){
                            var group = data.order_archives.group;
                            $.each(group,function(k,v){
                                archives_group_html += "<tr>"
                                +"<td>"+v["fields"]["thickness"]+"</td>"
                                +"<td>"+v["fields"]["color"]+"</td>"
                                +"<td>"+v["fields"]["model"]+"</td>"
                                +"<td>"+v["number_sum"]+"</td>"
                                +"<td>"+v["row_area_sum"]+"</td>"
                                +"</tr>";
                                
                                //颜色统计
                                var color_field = v["fields"]["color"];
                                if(!archives_color_obj.hasOwnProperty(color_field)){
                                    archives_color_obj[color_field] = {"number_sum":0,"row_area_sum":0};
                                }
                                archives_color_obj[color_field]["number_sum"] += parseFloat(v["number_sum"]);
                                archives_color_obj[color_field]["row_area_sum"] += parseFloat(v["row_area_sum"]);
                            });
                            $("#table-list_archives_group").find("tbody").html(archives_group_html);
                            
                            //颜色统计
                            var archives_color_html = "";
                            $.each(archives_color_obj,function(ck,cv){
                                archives_color_html += "<tr>"
                                +"<td>"+ck+"</td>"
                                +"<td>"+cv["number_sum"]+"</td>"
                                +"<td>"+(Math.round(cv["row_area_sum"]*1000000)/1000000)+"</td>"
                                +"</tr>";
                                
                            });
                            $("#table-list_archives_color").find("tbody").html(archives_color_html);
                        }
                        
                    });
                };
        
            </script>';

        $table_head = [array_values(ArchivesModel::$fields)];
        $table_data = ArchivesModel::getList($id);
        if($table_data){
            $table_data[] = ["<div style='text-align: right'>合计数量：<a style='font-size: 25px;'>".round(Db::name('mill_order_archives')->where('order_id='.$id)->sum('number'),6)."</a>  合计面积(M²)：<a style='font-size: 25px;'>".round(Db::name('mill_order_archives')->where('order_id='.$id)->sum('row_area'),6)."[13:1]</a></div>"];
        }
        $table_extra_head = [['名字','数量',]];
        $table_extra_data = ArchivesModel::getList($id,'model_sn,number','','',[],[['a.order_id','=',$id],['a.extra','=',1]],'mill_order_archives');

        $table_group_head = [['厚度','颜色','铝板版型','合计件数','合计面积',]];
        $table_group_data = ArchivesModel::getList($id,'thickness,color,model,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','thickness,color,model',[],[],'mill_order_archives');

        $table_color_head = [['颜色','合计件数','合计面积',]];
        $table_color_data = ArchivesModel::getList($id,'color,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','color',[],[],'mill_order_archives');

        $title = $isEdit?'上传面积表':'面积表详情';
        $hideBtn = $isEdit?'':['submit'];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItem('hidden', 'order_pid')
            ->addFormItem('hidden', 'is_pid')
            ->addFormItem('hidden', 'client_id')
            ->addFormItem('hidden', 'money_str')
            ->addFormItem('hidden', 'nickname')
            ->addFormItem('hidden', 'mobile')
            ->addFormItem('hidden', 'contract')
            ->addFormItem('hidden', 'note')
            ->addFormItem('hidden', 'create_time')
            ->addFormItem('hidden', 'update_time')
            ->addFormItem('hidden', 'archives_bill_time')
            ->addFormItem('hidden', 'back')
            ->addFormItem('hidden', 'archives_sn')
            ->addFormItem('hidden', 'back_status')
            ->addFormItem('hidden', 'back_status_verify_uid')
            ->addFormItem('hidden', 'back_status_time')
            /*
            ->addFormItem('hidden', 'back_drawing')
            ->addFormItem('hidden', 'back_open')
            ->addFormItem('hidden', 'waiback_status')
            ->addFormItem('hidden', 'waiback_status_verify_uid')
            ->addFormItem('hidden', 'waiback_drawing')
            ->addFormItem('hidden', 'waiback_open')
            ->addFormItem('hidden', 'waiback_status_time')*/
            ->addFormItems([ // 批量添加表单项
                ['file:12', 'archives_drawing', '面积计算表'],
                ['text:4', 'engineering', '工程名称'],
                //['text:4', 'archives_money', '履定价格'],
                //['text:4', 'archives_handle', '业务经办人'],
                //['text:4', 'archives_open', '计算'],
                //['date:4', 'archives_sign_time', '日期'],
                //['text:4', 'archives_plan', '设计师'],
                //['text:4', 'archives_sn', '档案号'],
                ['text:4', 'order_sn', '工程编号'],
                ['text:4', 'batch', '批次'],
                //['text:4', 'order_sn_off', '订单编号'],
                //['text:4', 'archives_type', '保护膜类型'],
                //['date:4', 'archives_bill_time', '发单日期'],
                ['complexTable:12', 'list_archives', '面积表', $table_data, $table_head],
                //['complexTable:6', 'list_archives_extra', '配件统计', $table_extra_data, $table_extra_head],
                ['complexTable:12', 'list_archives_group', '面积表统计', $table_group_data, $table_group_head],
                ['complexTable:12', 'list_archives_color', '颜色统计', $table_color_data, $table_color_head],
            ])
            ->setFormData($info)
            ->layout(['archives_drawing'=>12])
            ->setExtraJs($js)
            ->hideBtn($hideBtn)
            ->fetch();
    }

    /**
     * 获取面积表文档信息并编译
     */
    public function archivesDrawing()
    {

        // 接收附件 ID
        $id = input('param.id');
        // 获取附件 ID 完整路径
        $file = get_file_path($id);
        //$full_path = 'D:/office/phpstudy_pro/WWW/xxy/public/uploads/files/20210611/49dc8272891a2dbdc3396fc055d8017c.xls';
        if(strpos(getcwd(),'public') && strpos($file,'public'))$file = explode('public',$file)[1];
        $full_path = getcwd() . $file;

        $head_table = [
            'sheet'         =>  '面积表',
            'rowStart'      =>  2,
            'rowEnd'        =>  2,
            'table'         =>  'order',
            'fields'        =>  [
                'C-2'       =>  'engineering',
                'C-3'       =>  'archives_open',
                'R-3'       =>  'archives_handle',
                'R-4'       =>  'archives_version',
                'R-5'       =>  'archives_sign_time',
                //'G-2'       =>  'archives_bill_time',
                'I-2'       =>  'order_sn',
                'N-2'       =>  'engineering_full',
                'R-2'       =>  'batch',
            ]
        ];
        $archives_table = [
            'sheet'         =>  '面积表',
            'rowStart'      =>  7,
            //'rowEnd'        =>  5,
            'table'         =>  'order_archives',
            'fields'        =>  [
                'A'         =>  'sort',
                'B'         =>  'model_sn',
                'C'         =>  'page',
                'D'         =>  'long',
                'E'         =>  'high',
                'F'         =>  'number',
                'G'         =>  'one_area',
                'H'         =>  'row_area',
                'N'         =>  'color',
                'O'         =>  'slot',
                'P'         =>  'weld',
                //'Q'         =>  'plank',
                'Q'         =>  'thickness',
                'R'         =>  'model',
            ],
            'group'         =>  [
                'fields'    =>  ['thickness','color','model'],
                'sum'       =>  ['number','row_area']
            ]
        ];
        $sheet_read_arr = [$head_table,$archives_table];
        $import = plugin_action('Excel/Excel/importarchives', [$full_path,$sheet_read_arr]);

        echo json_encode($import,JSON_UNESCAPED_UNICODE);exit;

    }
    /**
     * 编辑面积表
     * @param null $id 工程id
     * @param bool $isEdit 是否可编辑
     * @return mixed
     */
    public function archivesEdit($id=null,$isEdit=true)
    {

        if ($this->request->isPost() && $isEdit) {
            $data = $this->request->post();
            //是否为新增面积表，是新增面积表，则自动新增工程
            $is_pid = $data['is_pid'];
            $archives_lists = isset($data['archives_lists'])?$data['archives_lists']:'';
            unset($data['archives_lists']);
            unset($data['is_pid']);
            // 验证
            $result = $this->validate($data, 'Order');
            if(empty($data['archives_drawing']))$this->error('请上传面积表');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            if(empty($data['archives_bill_time']))$data['archives_bill_time'] = date('Y-m-d H:i:s');
            if(empty($data['archives_sign_time']))$data['archives_sign_time'] = date('Y-m-d H:i:s');
            $data['archives_bill_time'] = str_replace(".","-",$data['archives_bill_time']);
            $data['archives_sign_time'] = str_replace(".","-",$data['archives_sign_time']);

            $data['archives_bill_time'] = strtotime($data['archives_bill_time']);
            $data['archives_sign_time'] = strtotime($data['archives_sign_time']);
            preg_match('/\d+/',$data['batch'],$batch);
            $data['archives_sn'] = "{$data['order_sn']}-{$batch[0]}";

            //验证档案号是否唯一
            $isArchives_sn = Db::name('mill_order')->where(['archives_sn'=>$data['archives_sn']])->value('id');

            if($is_pid){
                $order_sn = Db::name('mill_order')->where(['id'=>$data['order_pid']])->value('order_sn');
                //if($isArchives_sn)$this->error('该批次已存在');
                if($isArchives_sn)$this->error('该档案号已存在');
                //if($order_sn != $data['order_sn'])$this->error('工程号不匹配');

                unset($data['id']);
                $re = OrderModel::create($data);
                if(!empty($re['id']))$id = $re['id'];
            }
            else {
                $info = Db::name('mill_order')->where(['id'=>$data['id']])->find();
                //if(!empty($isArchives_sn) && $isArchives_sn != $data['id'])$this->error('该批次已存在');
                if(!empty($isArchives_sn) && $isArchives_sn != $data['id'])$this->error('该档案号已存在');
                //if(!empty($info['order_sn']) && $info['order_sn'] != $data['order_sn'])$this->error('工程号不匹配');
                if(!empty($info['archives_sn']) && $info['archives_sn'] != $data['archives_sn'])$this->error('档案号不匹配');

                $is_speed = Db::name('mill_order_archives_give')->where([['order_id','=',$id],['status','<>',0]])->count();

                $re = OrderModel::update($data);
            }
            // 更新数据
            if ($re) {

                //更新面积表
                if(!empty($archives_lists)){
                    //if(empty($archives_lists[0]['sort']))$this->error('请上传序号');
                    //未投入生产的直接重新录入
                    if(empty($is_speed) && 1==2){//暂时作废
                        Db::name('mill_order_archives')->where('order_id='.$id)->delete();//删除已存在的数据
                        Db::name('mill_order_archives_give')->where('order_id='.$id)->delete();//删除已存在的数据

                        Db::name('mill_order_archives')->insertAll($archives_lists);//重新批量录入
                    }
                    //已投入生产的则循环遍历更新
                    else{
                        //获取所有面积表序列
                        $sort_list = Db::name('mill_order_archives')->where(['order_id'=>$id])->order('sort asc')->column('sort');
                        if(!empty($sort_list))$sort_list = array_flip($sort_list);
                        //获取最后一件产品的序列
                        $sort = Db::name('mill_order_archives_give')
                            ->where(['order_id'=>$id])
                            ->order('sort desc')
                            ->value('sort');

                        foreach ($archives_lists as $av){
                            //过滤未被删减的面积表序列
                            if(!empty($sort_list))unset($sort_list[$av['sort']]);

                            $extra = empty($av['extra'])?'':$av['extra'];
                            //录入配件产品
                            if($extra == 1 && 1==2){
                                $archives_where = [
                                    'order_id'  =>  $id,
                                    'sort'  =>  $av['sort'],
                                ];
                                $archives = Db::name('mill_order_archives_extra')->where($archives_where)->find();

                                //录入
                                if(empty($archives)) Db::name('mill_order_archives_extra')->insert($av);
                                //更新
                                else Db::name('mill_order_archives_extra')->where(['id'=>$archives['id']])->update($av);
                                //跳过本次循环
                                continue;
                            }
                            $archives_where = [
                                'order_id'  =>  $id,
                                'sort'  =>  $av['sort'],
                            ];
                            $archives = Db::name('mill_order_archives')->where($archives_where)->find();
                            //录入
                            if(empty($archives)) {
                                $archives['id'] = Db::name('mill_order_archives')->insertGetId($av);
                                //后续新增的面积表序列，且有已被投入生产的产品，则插入新增的产品
                                if($sort){
                                    $archives = Db::name('mill_order_archives')->where($archives_where)->find();
                                    //获取最后一件产品
                                    $give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                                    $count_x = $av['number'];
                                    if(!empty($give)){

                                        //获取该序列最后一件产品的序号
                                        $counter_last = Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->order('sort desc')->value('counter');
                                        $counter_last = intval($counter_last);
                                        for($i=($counter_last+1);$i<=($counter_last+$count_x);$i++){
                                            $counter = $i;//计件数
                                            $sort++;//计件数+1
                                            $add = [
                                                'order_id'              =>  $archives['order_id'],
                                                'order_pid'             =>  $archives['order_pid'],
                                                'archives_id'           =>  $archives['id'],
                                                'archives_sn'           =>  $archives['archives_sn'],
                                                'counter'               =>  $counter,
                                                'give_date'             =>  $give['give_date'],
                                                'batch'                 =>  $give['batch'],
                                                'sort'                  =>  $sort,
                                                'give_sn'               =>  GiveModel::giveSn($give['give_date'],$give['batch'],$sort),
                                            ];

                                            Db::name('mill_order_archives_give')->insert($add);
                                        }
                                    }
                                }

                            }
                            //更新
                            else{
                                //有产品增加
                                if($av['number'] > $archives['number']){
                                    //获取最后一件产品
                                    $give_where = [
                                        'archives_id'   =>  $archives['id'],
                                    ];
                                    $give = Db::name('mill_order_archives_give')->where($give_where)->order('counter desc')->find();
                                    if(empty($give)){
                                        $give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                                        $archives['number'] = 0;
                                    }
                                    $count_x = $av['number']-$archives['number'];
                                    if(!empty($give)){

                                        //获取该序列最后一件产品的序号
                                        $counter_last = Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->order('sort desc')->value('counter');
                                        $counter_last = intval($counter_last);
                                        for($i=($counter_last+1);$i<=($counter_last+$count_x);$i++){
                                            $counter = $i;//计件数
                                            $sort++;//计件数+1
                                            $add = [
                                                'order_id'              =>  $archives['order_id'],
                                                'order_pid'             =>  $archives['order_pid'],
                                                'archives_id'           =>  $archives['id'],
                                                'archives_sn'           =>  $archives['archives_sn'],
                                                'counter'               =>  $counter,
                                                'give_date'             =>  $give['give_date'],
                                                'batch'                 =>  $give['batch'],
                                                'sort'                  =>  $sort,
                                                'give_sn'               =>  GiveModel::giveSn($give['give_date'],$give['batch'],$sort),
                                            ];

                                            Db::name('mill_order_archives_give')->insert($add);
                                        }
                                    }
                                }
                                //有产品减少
                                elseif($av['number'] < $archives['number']){
                                    //获取最初始状态的产品
                                    $give_where = [
                                        ['archives_id','=',$archives['id']],
                                        ['quality_status','>=','-1'],
                                    ];
                                    $count_x = $archives['number']-$av['number'];
                                    $give_id = Db::name('mill_order_archives_give')
                                        ->where($give_where)
                                        ->order('status asc,sort desc')
                                        ->limit($count_x)
                                        ->column('id');
                                    $give_update_x = ['quality_status'=>'-3',];
                                    if(!empty($give_id)){
                                        $give_id = implode(',',$give_id);
                                        Db::name('mill_order_archives_give')->where([['id','in',$give_id]])->update($give_update_x);
                                    }
                                }
                                //更新
                                Db::name('mill_order_archives')->where(['id'=>$archives['id']])->update($av);
                            }
                        }
                        //清除删减的面积表序列
                        if(!empty($sort_list)){
                            $sort_list = array_keys($sort_list);
                            $sort_ids = Db::name('mill_order_archives')->where([['order_id','=',$id],['sort','in',implode(',',$sort_list)]])->order('sort asc')->column('id');
                            if(!empty($sort_ids)){
                                $sort_ids = implode(',',$sort_ids);
                                Db::name('mill_order_archives')->where("id in ({$sort_ids})")->delete();//删除已存在的数据
                                Db::name('mill_order_archives_give')->where("archives_id in ({$sort_ids})")->delete();//删除已存在的数据
                            }
                            //配件
                            $sort_ids_extra = Db::name('mill_order_archives_extra')->where([['order_id','=',$id],['sort','in',implode(',',$sort_list)]])->order('sort asc')->column('id');
                            if(!empty($sort_ids_extra)){
                                $sort_ids_extra = implode(',',$sort_ids_extra);
                                Db::name('mill_order_archives_extra')->where("id in ({$sort_ids_extra})")->delete();//删除已存在的数据
                            }
                        }
                    }

                    if($is_pid && cookie('__encry__')){
                        Db::name('mill_order_archives')->where(['encry'=>cookie('__encry__')])->update(['order_id'=>$id,'encry'=>'']);
                        cookie('__encry__','');
                    }
                }
                //更新档案号
                Db::name('mill_order_archives')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);
                Db::name('mill_order_archives_give')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);
                Db::name('mill_order_archives_extra')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);

                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        $id = input('param.id');
        $order_pid = input('param.order_pid');
        if(empty($id) && empty($order_pid))$this->error('错误操作');
        $is_pid = false;
        $encry = '';//加密串
        // 获取数据
        if($id)$info = OrderModel::find($id);
        elseif ($order_pid){
            $info = OrderModel::where(['order_pid'=>$order_pid])->find();
            $is_pid = true;
            //生成加密串
            $encry = Auth::token();
            cookie('__encry__', $encry);

            unset($info['archives_drawing']);
            unset($info['archives_bill_time']);
            unset($info['archives_sign_time']);
            unset($info['batch']);
            unset($info['archives_handle']);
            unset($info['archives_open']);
            unset($info['archives_plan']);
            unset($info['archives_sn']);
            unset($info['order_sn']);
            unset($info['order_sn_off']);
            unset($info['archives_version']);
            unset($info['archives_type']);
            unset($info['give_status']);
            unset($info['give_pro']);
            unset($info['archives_del_status']);
            unset($info['archives_del_status_verify_uid']);
            unset($info['archives_del_status_time']);
            unset($info['archives_del_status_note']);
            unset($info['urgent_status']);
            unset($info['urgent_status_time']);
        }
        $info['is_pid'] = $is_pid;
        $info['archives_drawing'] = empty($info['archives_drawing'])?'':$info['archives_drawing'];
        $info['archives_bill_time'] = empty($info['archives_bill_time'])?'':$info['archives_bill_time'];
        $info['archives_sign_time'] = empty($info['archives_sign_time'])?'':$info['archives_sign_time'];
        //js
        $js = '<script type="text/javascript">
                //上传面积表成功后的回调
                var dp_file_upload_success_archives_drawing = function () {
                    //面积表文档ID
                    var archives_drawing = $("input[name=archives_drawing]").val();
                    //获取面积表文档信息并编译
                    $.ajax({
                        url: \''.url("archivesDrawing").'?id=\'+archives_drawing,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        
                        //更新工程信息
                        var order = [];
                        if(data.order.lists[0]){
                            order = data.order.lists[0];
                            //---------去掉档案号里的批次 start---------------
                            var order_sn_arr = order.order_sn.split("-");
                            order.order_sn = "";
                            for (var i = 0; i < (order_sn_arr.length-1); ++i) {
                                order.order_sn += "-"+order_sn_arr[i];
                            }
                            order.order_sn = order.order_sn.replace(/(^-)|(-$)/g,\'\');
                            //---------去掉档案号里的批次 end------------------
                            
                            order.archives_sn = order.order_sn+"-"+order.batch;
                            //$("input[name=engineering]").val(order.engineering);
                            $("input[name=engineering_full]").val(order.engineering_full);
                            $("input[name=order_sn]").val(order.order_sn);
                            $("input[name=order_sn_off]").val(order.order_sn_off);
                            $("input[name=archives_version]").val(order.archives_version);
                            $("input[name=archives_handle]").val(order.archives_handle);
                            //$("input[name=archives_sn]").val(order.archives_sn);
                            $("input[name=archives_bill_time]").val(order.archives_bill_time);
                            $("input[name=archives_sign_time]").val(order.archives_sign_time);
                            $("input[name=archives_open]").val(order.archives_open);
                            $("input[name=batch]").val(order.batch);
                        }
                        
                        //更新面积表信息
                        var archives_html = "";
                        if(data.order_archives.lists){
                            var lists = data.order_archives.lists;
                            
                            //序号
                            var sort_arr = [];
                            //铝板编号
                            var model_sn_arr = [];
                            //配件统计
                            var archives_extra_html = "";
                            //新增面积表时，判断序号是否连号
                            //var archives_drawing = "'.$info['archives_drawing'].'";//是否为新增
                            var sort_i = 1;//序号连号计数器
                            var number_sum = 0;
                            var row_area_sum = 0;
                            $.each(lists,function(i,v){
                                v["plank"] = v["thickness"];
                                var model_sn = v["model_sn"];
                                //判断铝板编号是否重复
                                if(model_sn_arr.includes(model_sn)){
                                    Dolphin.notify("铝板编号【"+model_sn+"】有重复", "danger");
                                }
                                model_sn_arr.push(model_sn);
                                var k = v["sort"];
                                if(k == ""||k == "null"){
                                    Dolphin.notify("序号不能为空", "danger");
                                }
                                //判断序号是否重复
                                if(sort_arr.includes(k)){
                                    Dolphin.notify("序号【"+k+"】有重复", "danger");
                                }
                                sort_arr.push(k);
                                //判断序号是否连号
                                //if((archives_drawing == ""||archives_drawing == "null")&&(sort_i!=k)){
                                if(sort_i!=k){
                                    //Dolphin.notify("序号["+k+"]不连号", "danger");
                                }
                                v["row_area"] = Math.round((v["number"]*v["one_area"])*1000000)/1000000;
                                v["slot"] = Math.round((v["slot"]/v["number"])*1000000)/1000000;
                                v["weld"] = Math.round((v["weld"]/v["number"])*1000000)/1000000;
                                archives_html += "<tr><input type=\'hidden\' name=\'archives_lists["+k+"][order_id]\' value=\''.$id.'\'><input type=\'hidden\' name=\'archives_lists["+k+"][order_pid]\' value=\''.$info['order_pid'].'\'><input type=\'hidden\' name=\'archives_lists["+k+"][encry]\' value=\''.$encry.'\'><input type=\'hidden\' name=\'archives_lists["+k+"][archives_sn]\' value=\'"+order.archives_sn+"\'>"
                                
                                +"<input type=\'hidden\' name=\'archives_lists["+k+"][slot]\' value=\'"+v["slot"]+"\'>"
                                +"<input type=\'hidden\' name=\'archives_lists["+k+"][weld]\' value=\'"+v["weld"]+"\'>"
                                
                                +"<td>"+v["sort"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][sort]\' value=\'"+v["sort"]+"\'></td>"
                                +"<td>"+v["model_sn"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][model_sn]\' value=\'"+v["model_sn"]+"\'></td>"
                                +"<td>"+v["page"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][page]\' value=\'"+v["page"]+"\'></td>"
                                +"<td>"+v["number"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][number]\' value=\'"+v["number"]+"\'></td>"
                                +"<td>"+v["long"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][long]\' value=\'"+v["long"]+"\'></td>"
                                +"<td>"+v["high"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][high]\' value=\'"+v["high"]+"\'></td>"
                                +"<td>"+v["one_area"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][one_area]\' value=\'"+v["one_area"]+"\'></td>"
                                +"<td>"+v["row_area"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][row_area]\' value=\'"+v["row_area"]+"\'></td>"
                                +"<td>"+v["color"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][color]\' value=\'"+v["color"]+"\'></td>"
                                +"<td>"+v["thickness"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][thickness]\' value=\'"+v["thickness"]+"\'></td>"
                                +"<td>"+v["plank"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][plank]\' value=\'"+v["plank"]+"\'></td>"
                                +"<td>"+v["model"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][model]\' value=\'"+v["model"]+"\'></td>"
                                +"</tr>";
                                
                                //配件组装
                                if(v["extra"] == 1){
                                    archives_extra_html += "<tr>"
                                    +"<td>"+v["model_sn"]+"</td>"
                                    +"<td>"+v["number"]+"</td>"
                                    +"</tr>";
                                }
                                
                                number_sum += parseFloat(v["number"]);
                                row_area_sum += parseFloat(v["row_area"]);
                                sort_i ++;
                            });
                            
                            //组装
                            archives_html += "<tr><td colspan=\'13\' style=\'text-align: right;\'>合计数量：<a style=\'font-size: 25px;\'>"+number_sum+"</a>  合计面积(M²)：<a style=\'font-size: 25px;\'>"+Math.round(row_area_sum*1000000)/1000000+"</a></td></tr>";
                            $("#table-list_archives").find("tbody").html(archives_html);
                        }
                        
                        //配件统计
                        $("#table-list_archives_extra").find("tbody").html(archives_extra_html);
                        
                        //更新统计信息
                        var archives_group_html = "";
                        var archives_color_obj = {};//颜色统计
                        if(data.order_archives.group){
                            var group = data.order_archives.group;
                            $.each(group,function(k,v){
                                archives_group_html += "<tr>"
                                +"<td>"+v["fields"]["thickness"]+"</td>"
                                +"<td>"+v["fields"]["color"]+"</td>"
                                +"<td>"+v["fields"]["model"]+"</td>"
                                +"<td>"+v["number_sum"]+"</td>"
                                +"<td>"+v["row_area_sum"]+"</td>"
                                +"</tr>";
                                
                                //颜色统计
                                var color_field = v["fields"]["color"];
                                if(!archives_color_obj.hasOwnProperty(color_field)){
                                    archives_color_obj[color_field] = {"number_sum":0,"row_area_sum":0};
                                }
                                archives_color_obj[color_field]["number_sum"] += parseFloat(v["number_sum"]);
                                archives_color_obj[color_field]["row_area_sum"] += parseFloat(v["row_area_sum"]);
                            });
                            $("#table-list_archives_group").find("tbody").html(archives_group_html);
                            
                            //颜色统计
                            var archives_color_html = "";
                            $.each(archives_color_obj,function(ck,cv){
                                archives_color_html += "<tr>"
                                +"<td>"+ck+"</td>"
                                +"<td>"+cv["number_sum"]+"</td>"
                                +"<td>"+(Math.round(cv["row_area_sum"]*1000000)/1000000)+"</td>"
                                +"</tr>";
                                
                            });
                            $("#table-list_archives_color").find("tbody").html(archives_color_html);
                        }
                        
                    });
                };
        
            </script>';

        $table_head = [array_values(ArchivesModel::$fields)];
        $table_data = ArchivesModel::getList($id);
        if($table_data){
            $table_data[] = ["<div style='text-align: right'>合计数量：<a style='font-size: 25px;'>".round(Db::name('mill_order_archives')->where('order_id='.$id)->sum('number'),6)."</a>  合计面积(M²)：<a style='font-size: 25px;'>".round(Db::name('mill_order_archives')->where('order_id='.$id)->sum('row_area'),6)."[13:1]</a></div>"];
        }
        $table_extra_head = [['名字','数量',]];
        $table_extra_data = ArchivesModel::getList($id,'model_sn,number','','',[],[['a.order_id','=',$id],['a.extra','=',1]],'mill_order_archives');

        $table_group_head = [['厚度','颜色','铝板版型','合计件数','合计面积',]];
        $table_group_data = ArchivesModel::getList($id,'thickness,color,model,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','thickness,color,model',[],[],'mill_order_archives');

        $table_color_head = [['颜色','合计件数','合计面积',]];
        $table_color_data = ArchivesModel::getList($id,'color,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','color',[],[],'mill_order_archives');

        $title = $isEdit?'上传面积表':'面积表详情';
        $hideBtn = $isEdit?'':['submit'];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItem('hidden', 'order_pid')
            ->addFormItem('hidden', 'is_pid')
            ->addFormItem('hidden', 'client_id')
            ->addFormItem('hidden', 'money_str')
            ->addFormItem('hidden', 'nickname')
            ->addFormItem('hidden', 'mobile')
            ->addFormItem('hidden', 'contract')
            ->addFormItem('hidden', 'note')
            ->addFormItem('hidden', 'create_time')
            ->addFormItem('hidden', 'update_time')
            ->addFormItem('hidden', 'archives_bill_time')
            ->addFormItem('hidden', 'back')
            ->addFormItem('hidden', 'archives_sn')
            ->addFormItem('hidden', 'engineering_full')
            /*->addFormItem('hidden', 'back_status')
            ->addFormItem('hidden', 'back_status_verify_uid')
            ->addFormItem('hidden', 'back_drawing')
            ->addFormItem('hidden', 'back_open')
            ->addFormItem('hidden', 'back_status_time')
            ->addFormItem('hidden', 'waiback_status')
            ->addFormItem('hidden', 'waiback_status_verify_uid')
            ->addFormItem('hidden', 'waiback_drawing')
            ->addFormItem('hidden', 'waiback_open')
            ->addFormItem('hidden', 'waiback_status_time')*/
            ->addFormItems([ // 批量添加表单项
                ['file:12', 'archives_drawing', '面积计算表'],
                ['text:4', 'engineering', '工程名称'],
                //['text:4', 'archives_money', '履定价格'],
                ['text:4', 'archives_open', '计算'],
                ['date:4', 'archives_sign_time', '日期'],
                //['text:4', 'archives_plan', '设计师'],
                //['text:4', 'archives_sn', '档案号'],
                ['text:4', 'order_sn', '工程编号'],
                ['text:4', 'batch', '批次'],
                ['text:4', 'archives_version', '版本'],
                ['text:4', 'archives_handle', '业务经办人'],
                //['text:4', 'order_sn_off', '订单编号'],
                //['text:4', 'archives_type', '保护膜类型'],
                //['date:4', 'archives_bill_time', '发单日期'],
                ['complexTable:12', 'list_archives', '面积表', $table_data, $table_head],
                //['complexTable:6', 'list_archives_extra', '配件统计', $table_extra_data, $table_extra_head],
                ['complexTable:12', 'list_archives_group', '面积表统计', $table_group_data, $table_group_head],
                ['complexTable:12', 'list_archives_color', '颜色统计', $table_color_data, $table_color_head],
            ])
            ->setFormData($info)
            ->layout(['archives_drawing'=>12])
            ->setExtraJs($js)
            ->hideBtn($hideBtn)
            ->fetch();
    }
    /**
     * 面积表详情
     * @param null $id 工程id
     * @return mixed
     */
    public function archivesShow($id=null)
    {

        $id = input('param.id');

        return $this->archivesEdit($id,false);
    }
    public function archivesShow2(){
        return $this->archivesShow();
    }
    /**
     * 编辑产品信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 获取查询条件
        $id = input('order_id');
        $map[] = ['order_id','=',$id];

        // 数据列表
        $_listRows = input('list_rows',GiveModel::$_listRows);
        $data_list = Db::name('mill_order_archives')
            ->where($map)
            ->order('sort')
            ->select();
        //->paginate($_listRows);

        //工程信息
        $order = Db::name('mill_order')->where(['id'=>$id])->find();

        //JS
        $js = '';
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("{$order['engineering']} {$order['archives_sn']} 面积表") // 页面标题
            ->setTableName('mill_order_archives') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['sort', '编号'],
                ['page', '图纸页码','text.edit'],
                ['model_sn', '铝板编号','text.edit'],
                ['number', '数量'],
                ['cutting', '开料L','text.edit'],
                ['size', '开料H','text.edit'],
                ['one_area', '单件面积M²','text.edit'],
                ['row_area', '合计面积M²','text.edit'],
                ['long', 'L(MM)','text.edit'],
                ['high', 'H(MM)','text.edit'],
                ['color', '颜色','text.edit'],
                ['thickness', '板厚MM','text.edit'],
                ['model', '铝板板型','text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->setColumnWidth([
                'sort'    =>  50,
                'page'    =>  65,
                'cutting'    =>  50,
                'number'    =>  50,
                'size'    =>  50,
                'one_area'    =>  80,
                'row_area'    =>  80,
                'long'    =>  52,
                'high'    =>  52,
                'color'    =>  120,
                'thickness'    =>  60,
                'model_sn'    =>  130,
            ])// 设置列宽
            ->setExtraJs($js)
            ->addTopButtons(['addGive' => ['title' => '新增单个产品','class'=>'btn btn-default','href'=>url('addGive',['order_id'=>$id])]]) // 批量添加顶部按钮
            ->addTopButtons(['orderEdit' => ['title' => '编辑工程','class'=>'btn btn-primary','href'=>url('orderEdit',['id'=>$id])]]) // 批量添加顶部按钮
            ->addRightButton('archivesGive',['title' => '打印','href' => url('mill/give/archivesgive2',['id' => '__order_id__','archives_id'=>'__id__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('archivesGive',['title' => '打印(带LOGO)','href' => url('mill/give/archivesgive2',['id' => '__order_id__','archives_id'=>'__id__','watermark'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('delGive',['title' => '删除','href' => url('delGive',['archives_id'=>'__id__']),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            //->noPages()
            ->fetch(); // 渲染模板
    }
    /**
     * 编辑工程面积表
     * @param null $id 工程id
     * @param bool $isEdit 是否可编辑
     * @return mixed
     */
    public function orderEdit()
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            unset($data['archives_lists']);
            unset($data['is_pid']);
            // 验证
            $result = $this->validate($data, 'Order');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['archives_bill_time'] = strtotime($data['archives_bill_time']);
            $data['archives_sign_time'] = strtotime($data['archives_sign_time']);

            //验证档案号是否唯一
            $isArchives_sn = Db::name('mill_order')->where(['archives_sn'=>$data['archives_sn']])->value('id');

            if(!empty($isArchives_sn) && $isArchives_sn != $data['id'])$this->error('该档案号已存在');
            // 更新数据
            if (OrderModel::update($data)){
                Db::name('mill_order_archives')->where(['order_id'=>$data['id']])->update(['archives_sn'=>$data['archives_sn']]);
                Db::name('mill_order_archives_give')->where(['order_id'=>$data['id']])->update(['archives_sn'=>$data['archives_sn']]);
                $this->success('编辑成功', cookie('__forward__'));
            }

            $this->error('编辑失败');
        }

        $id = input('param.id');
        if(empty($id))$this->error('错误操作');
        // 获取数据
        if($id)$info = OrderModel::find($id);
        $info['archives_bill_time'] = empty($info['archives_bill_time'])?'':$info['archives_bill_time'];
        $info['archives_sign_time'] = empty($info['archives_sign_time'])?'':$info['archives_sign_time'];
        //js
        $js = '';

        $title = '编辑工程';
        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItem('hidden', 'order_pid')
            ->addFormItem('hidden', 'client_id')
            ->addFormItem('hidden', 'money_str')
            ->addFormItem('hidden', 'nickname')
            ->addFormItem('hidden', 'mobile')
            ->addFormItem('hidden', 'contract')
            ->addFormItem('hidden', 'note')
            ->addFormItem('hidden', 'create_time')
            ->addFormItem('hidden', 'update_time')
            ->addFormItem('hidden', 'back')
            /*->addFormItem('hidden', 'back_status')
            ->addFormItem('hidden', 'back_status_verify_uid')
            ->addFormItem('hidden', 'back_drawing')
            ->addFormItem('hidden', 'back_open')
            ->addFormItem('hidden', 'back_status_time')
            ->addFormItem('hidden', 'waiback_status')
            ->addFormItem('hidden', 'waiback_status_verify_uid')
            ->addFormItem('hidden', 'waiback_drawing')
            ->addFormItem('hidden', 'waiback_open')
            ->addFormItem('hidden', 'waiback_status_time')*/
            ->addFormItems([ // 批量添加表单项
                ['text:4', 'engineering', '工程名称'],
                ['text:4', 'archives_money', '履定价格'],
                ['text:4', 'archives_handle', '业务经办人'],
                ['text:4', 'archives_open', '计算'],
                ['text:4', 'archives_plan', '设计师'],
                ['text:4', 'batch', '下单批次'],
                ['text:4', 'archives_sn', '档案号'],
                ['text:4', 'order_sn', '工程编号'],
                ['date:4', 'archives_sign_time', '签字日期'],
                ['text:4', 'archives_version', '版本'],
                ['text:4', 'archives_type', '保护膜类型'],
                ['date:4', 'archives_bill_time', '发单日期'],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 新增单个面积表信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function addGive(){

        //工程号
        $order_id = input('order_id');

        //工程信息
        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();
        $order_str = "{$order['engineering']} {$order['archives_sn']}";

        //获取表格字段
        $archives_fields = ArchivesModel::$fields;

        if ($this->request->isPost()){

            $data = input();

            foreach ($data as $k=>$v){
                if(empty($v))$this->error("请输入{$archives_fields[$k]}");
            }
            unset($data['order_str']);
            unset($data['__token__']);


            $archives = Db::name('mill_order_archives')->where(['order_id'=>$data['order_id'],'sort'=>$data['sort']])->find();

            if(!empty($archives))$this->error('该序号已存在');

            $re = ArchivesModel::create($data);
            if ($re)$this->success('操作成功', cookie('__forward__'));
            $this->error('操作失败');
        }

        $formItems = [];
        foreach ($archives_fields as $k=>$v){
            $formItems[] = [
                'text:||||must',$k,$v
            ];
        }
        return ZBuilder::make('form')
            ->setPageTitle('新增单个产品') // 页面标题
            ->addStatic('order_str', '工程信息', '', $order_str,$order_str)
            ->addHidden('order_id',$order['id'])
            ->addHidden('order_pid',$order['order_pid'])
            ->addHidden('archives_sn',$order['archives_sn'])
            ->addFormItems($formItems)
            ->layout(['order_str'=>12])
            ->fetch();

    }
    /**
     * 删除单个面积表信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delGive(){

        $archives_id = input('archives_id');

        Db::name('mill_order_archives')->where(['id'=>$archives_id])->delete();
        Db::name('mill_order_archives_give')->where(['archives_id'=>$archives_id])->delete();

        $this->success('删除成功');

    }
    /**
     * 删除整个面积表信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delArchives(){

        $order_id = input('order_id');

        $give_count = Db::name('mill_order_archives_give')->where([['order_id','=',$order_id],['status','>',0]])->find();
        if(!empty($give_count)){
            Db::name('mill_order')->where(['id'=>$order_id])->update(['archives_del_status'=>0]);
            $this->error('该工程已开始生产');
        }
        Db::name('mill_order')->where(['id'=>$order_id])->update(['order_sn'=>'','archives_sn'=>'','archives_status'=>'','archives_del_status'=>0,'archives_drawing'=>0]);
        Db::name('mill_order_archives')->where(['order_id'=>$order_id])->delete();
        Db::name('mill_order_archives_extra')->where(['order_id'=>$order_id])->delete();
        Db::name('mill_order_archives_give')->where(['order_id'=>$order_id])->delete();

        $this->success('删除成功');

    }

    //--------------------------------------发货管理---------------------------------------------------
    /**
     * 发货列表页
     * @return mixed
     */
    public function deliver($address_status = '0,1,2',$_show_i = '',$title='发货记录')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //定时任务，超过24小时未确认发货，则自动发货
        GiveModel::taskSubGiveAddress();

        //发货状态
        $_address_status = GiveModel::$role[8]['status'][0];

        // 获取查询条件
        $map = $this->getMap();
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'client_id'){
                    $client_id = $v[2];
                    unset($map[$k]);
                }
            }
        }
        if(!empty($client_id)){
            $order_ids = Db::name('mill_order')->where([['client_id','=',$client_id]])->column('id');
            if(!empty($order_ids)){
                $order_ids = implode(',',array_values($order_ids));
                $map[] = ['g.order_id','in',$order_ids];
            }
        }
        $map = array_merge($map);
        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("group_concat(DISTINCT g.order_id) as order_ids,count(g.id) as address_sum,g.car_id,g.status5_time,g.address_time,g.address_date,g.address_sn,g.address_status")
            ->where($map)
            ->where("g.status={$_address_status} and g.address_sn != '' and g.address_status in ({$address_status})")
            ->group("g.address_sn")
            ->order('g.address_time desc')
            ->paginate()
            ->each(function ($v){

                $order = Db::name('mill_order')
                    ->field('*,group_concat(DISTINCT order_sn) as order_sn,group_concat(DISTINCT batch) as batch,group_concat(DISTINCT order_sn_off) as order_sn_off')
                    ->where([['id','in',$v['order_ids']]])
                    ->find();
                $v['order_sn'] = "{$order['order_sn']}（{$order['batch']}）";
                $v['batch'] = $order['batch'];
                $v['order_sn_off'] = $order['order_sn_off'];
                $v['client_id2'] = $order['client_id'];
                $v['plate_number'] = Db::name('mill_car')->where([['id','=',$v['car_id']]])->value('plate_number');

                $v = array_merge($order,$v);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setSearchArea([
                //['text:2', 'nickname', '司机联系人', 'like'],
                //['text:2', 'mobile', '司机联系电话', 'like'],
                ['select:2', 'g.car_id', '车牌号码','','',CarModel::getList()],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:3', 'g.archives_sn', '工程号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'o.batch', '发货批次', 'like'],
                //['daterange:2', 'g.status4_time', '发货日期'],
            ])
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['plate_number', '车牌号码'],
                ['address_sn', '发货单号'],
                ['status5_time', '开始装车时间','datetime'],
                ['address_time', '装车完成时间','datetime'],
                //['address_status', '状态',['0'=>'未装车完成','1'=>'已装车完成','2'=>'已装车完成']],
                ['address_status','状态','callback',function($value){
                    $status_arr = ['0'=>'未装车完成','1'=>'已装车完成','2'=>'已装车完成'];
                    $status = OrderModel::status_tag($value,$status_arr[$value]);

                    return $status;
                },'__data__'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['order_sn', '工程号'],
                ['address_sum', '产品总数量'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                //['give_sum','总数量'],
                //['give_sum4','已发货'],
                //['give_sum0_4','未发货'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('deliverSub',['title' => '确认装车','href' => url('deliverSub',['address_sn'=>'__address_sn__']),'icon'=>'','class'=>'btn btn-primary disable-dch ajax-get confirm'])
            ->addRightButton('deliverShow',['title' => '查看详情','href' => url('deliverShow'.$_show_i,['order_pid'=>'__order_pid__','address_sn' => '__address_sn__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('deliverShow2',['title' => '导出发货单','href' => url('deliverShow'.$_show_i,['order_pid'=>'__order_pid__','address_sn' => '__address_sn__','print'=>'2']),'class'=>'btn btn-default disable-dch','icon'=>'','target'=>'_blank'])
            //->addRightButton('deliverGiveShow',['title' => '产品明细','href' => url('deliverGiveShow'.$_show_i,['address_sn' => '__address_sn__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('deliverOrder',['title' => '产品明细','href' => url('deliverOrder'.$_show_i,['address_sn' => '__address_sn__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('deliverMerge',['title' => '合并发货单','href' => url('deliverMerge',['address_sn'=>'__address_sn__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['780px', '45%'], 'title' => ['合并发货单', 'font-size:24px;text-align: center;']])


            ->replaceRightButton(['address_status' => ['<>','0']],'',['deliverSub'])
            ->replaceRightButton(['address_status' => ['in','0,1']],'',['deliverShow2'])
            ->replaceRightButton(['address_status' => ['=','0']],'',['deliverShow','deliverShow2','deliverGiveShow','deliverMerge'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'address_date'  => 60,
                'archives_sn'  => 120,
                'engineering'  => 150,
                'batch'  => 80,
                'give_sum'  => 60,
                'give_sum4'  => 60,
                'give_sum0_4'  => 60,
                'right_button'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 发货中列表页
     * @return mixed
     */
    public function deliverIng()
    {
        $address_status = '0,1';
        return $this->deliver($address_status,'2','打印发货单');
    }
    /**
     * 发货记录列表页
     */
    public function deliverLog(){
        $address_status = '2';
        return $this->deliver($address_status,'','发货记录');
    }
    /**
     * 发货详情
     * @return mixed
     */
    public function deliverShow()
    {
        $config = new ConfigModel();
        //备注
        $deliver_note = $config->getConfig('mill_deliver_note');

        $address_sn = input('address_sn');//指定发货单号
        if(empty($address_sn))$this->error('错误操作');
        //打印 1:打印 2:导出
        $print = input('print');
        //显示单价 0:不显示 1:显示
        $is_price = input('is_price');

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $id = $data['id'];
            unset($data['print']);
            unset($data['id']);

            //更新发货单其他信息
            if(!empty($id))Db::name('mill_order_archives_address')->where('id='.$id)->update($data);
            else Db::name('mill_order_archives_address')->insert($data);

            //更新备注
            ConfigModel::where('name', 'mill_deliver_note')->update(['value' => $deliver_note]);
            //数据存储成功，并配置打印模板，进行打印
            $this->success('操作成功', admin_url('mill/order/delivershow',['address_sn'=>$address_sn,'print'=>$print]),'_blank');

            $this->error('操作失败');
        }

        $where[] = ['g.address_sn','=',$address_sn];
        $orders = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('group_concat(DISTINCT order_id) as order_ids,group_concat(DISTINCT archives_sn) as archives_sns')
            ->where($where)
            ->find();

        $table_fields = ArchivesModel::$fields4;

        unset($table_fields['status']);

        $table_data_span = [];
        if($print != 2){
            unset($table_fields['konghang']);
            unset($table_fields['long']);
            unset($table_fields['high']);

            //$table_data_span['color'] = "[3:1]";
            //$table_fields['color'] = "{$table_data_span['color']}{$table_fields['color']}";
            //$table_data_span['model'] = "[5:1]";
            //$table_fields['model'] = "{$table_data_span['model']}{$table_fields['model']}";
        }
        //显示单价 0:不显示 1:显示
        if(empty($is_price)){
            unset($table_fields['price']);
            unset($table_fields['price_sum']);
        }

        $fields = '';
        $fields2 = '';
        foreach ($table_fields as $k=>$v){
            if($k == 'number')$fields .= ",COUNT(g.id) as number";
            elseif ($k == 'archives_id')$fields .= ",g.{$k}";
            elseif ($k == 'one_area')$fields .= ",FORMAT(a.one_area,4) as one_area";
            elseif ($k == 'row_area')$fields .= ",(COUNT(g.id)*FORMAT(a.one_area,4)) as row_area";
            elseif ($k == 'batch')$fields .= ",o.{$k}";
            elseif ($k == 'pack')$fields .= ",'' AS pack";
            elseif ($k == 'make_model')$fields .= ",'' AS make_model";
            elseif ($k == 'price')$fields .= ",'' AS price";
            elseif ($k == 'price_sum')$fields .= ",'' AS price_sum";
            elseif ($k == 'order_sn_off')$fields .= ",o.{$k}";
            elseif ($k == 'create_time')$fields .= ",FROM_UNIXTIME(o.archives_bill_time,'%Y-%m-%d') as create_time";
            elseif (strpos($k,'konghang') !== false)$fields .= ",'' as {$k}";
            else $fields .= ",a.{$k}";

            if ($k == 'batch')$fields2 .= ",o.{$k}";
            elseif ($k == 'pack')$fields2 .= ",'' AS pack";
            elseif ($k == 'make_model')$fields2 .= ",'' AS make_model";
            elseif ($k == 'order_sn_off')$fields2 .= ",o.{$k}";
            elseif ($k == 'create_time')$fields2 .= ",FROM_UNIXTIME(o.create_time,'%Y-%m-%d') as create_time";
            elseif ($k == 'model_sn')$fields2 .= ",concat(a.{$k},'(配件)') as {$k}";
            elseif (strpos($k,'konghang') !== false)$fields2 .= ",'' as {$k}";
            else $fields2 .= ",a.{$k}";
        }
        $fields = trim($fields,',');
        $fields2 = trim($fields2,',');

        $group = 'a.id';
        $join = [['mill_order_archives_give g','a.id=g.archives_id','left'],['mill_order o','a.order_id=o.id','left']];

        $table_title = '';

        $table_head = [array_values($table_fields)];
        $table_data_list = ArchivesModel::getList(null,"{$fields},o.id",'a.order_id asc,CONVERT (REPLACE(a.sort,\'#\',\'999999\'),signed) ASC',$group,$join,$where);
        /*//配件
        $table_data_list2 = ArchivesModel::getList($order_id,"{$fields2},o.id",'a.order_id asc,CONVERT (REPLACE(a.sort,\'#\',\'999999\'),signed) ASC',[],[['mill_order o','a.order_id=o.id','left']],[['order_id','=',$order_id],['a.extra','=',1]],'mill_order_archives_new');
        $table_data_list = array_merge($table_data_list,$table_data_list2);*/

        //$table_group_field = 'o.id,a.thickness,a.color,a.model,a.plank,SUM(DISTINCT case when a.id then a.weld else 0 end ) AS weld_sum,SUM(DISTINCT case when a.id then a.slot else 0 end ) AS slot_sum,SUM(g.number) AS number_sum,SUM(a.one_area) AS area_sum';
        $table_group_field = 'o.id,a.thickness,a.color,a.model,a.plank,SUM(g.number) AS number_sum,SUM(a.one_area) AS area_sum';
        $table_group_data = ArchivesModel::getList(null,$table_group_field,'','o.id,a.thickness,a.color,a.model,a.plank',$join,$where);

        $table = [
            'head'          =>  $table_head[0],
            'data_span'     =>  $table_data_span,
            'data'          =>  $table_data_list,
            'group'         =>  $table_group_data,
        ];

        $address = Db::name('mill_order')
            ->alias('o')
            ->field('ad.*,o.order_pid,o.engineering,o.order_sn,o.batch,group_concat(DISTINCT o.batch) as batch,group_concat(DISTINCT o.id) as order_ids,group_concat(DISTINCT o.archives_sn) as archives_sns,cc.nickname as client_nickname,cc.mobile as client_mobile,cc.address as client_address,cc.company,cc.sales as handler,c.address_nickname,c.address_mobile,g.address_sn,g.address_date,ca.plate_number')
            ->leftJoin('mill_client cc','cc.id=o.client_id')
            ->leftJoin('mill_order_contract c','c.order_id=o.id')
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->leftJoin('mill_car ca','g.car_id=ca.id')
            ->leftJoin('mill_order_archives_address ad','ad.address_sn=g.address_sn')
            ->where([['g.address_sn','=',$address_sn]])
            ->group('g.address_sn')
            ->find();
        $address['note'] = $deliver_note;

        //新增发货单，配置基础信息
        if(empty($address['id'])){
            $address['car_plate_number'] = $address['plate_number'];
            $address['order_nickname'] = $address['address_nickname'];
            $address['order_mobile'] = $address['address_mobile'];
            $address['order_nickname1'] = $address['address_nickname'];
            $address['order_mobile1'] = $address['address_mobile'];
            $address['address'] = $address['client_address'];
            $address['order_ids'] = $orders['order_ids'];
            $address['archives_sns'] = $orders['archives_sns'];
            //获取最后一个发货人信息
            $give_status = GiveModel::$role[8]['status'][0];
            $last_give = Db::name('mill_order_archives_give')->where([['address_sn','=',$address_sn]])->order("status{$give_status}_time desc")->find();
            $user_id = trim(explode("_{$give_status}|",$last_give['status_flow'])[1],'_');
            $address['user_nickname'] = Db::name('admin_user')->where('id='.$user_id)->value('nickname');
            $address['order_pid'] = $last_give['order_pid'];
            $address['create_time'] = $last_give['address_time'];

        }
        elseif (empty($address['create_time']))$address['create_time'] = strtotime($address['address_date']);
        $address['is_price'] = $is_price;

        if(!empty($print)){
            Db::name('mill_order_archives_give')->where(['address_sn'=>$address_sn])->update(['address_status'=>2]);
            exit(AddressModel::toHtml($address,$table,$print));
        }

        $table_arr = AddressModel::fromTabale($address,$table);
        $table_data = $table_arr['data'];

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                  $("#table-list_archives").find("th").eq(8).css("width","130px");
                  $("#table-list_archives").find("th").eq(9).css("width","130px");
                  $("#table-list_archives").find("th").eq(10).css("width","130px");
                  
                  $("#table-list_archives_group").find("th").eq(4).css("width","130px");
                  $("#table-list_archives_group").find("th").eq(8).css("width","130px");
                  
                })
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('打印送货清单') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'address', $table_title, $table_data, ''],
                ['hidden','print',1],
            ])
            ->setExtraJs($js)
            ->setBtnTitle(['submit' => '提交打印'])
            ->fetch();
    }
    public function deliverShow2(){
        return $this->deliverShow();
    }
    /**
     * 发货工程列表页
     */
    public function deliverOrder($show_type=''){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $address_sn = input('address_sn');
        //发货状态
        $give_status = GiveModel::$role[8]['status'][0];

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['g.address_sn','=',$address_sn];
        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("'{$show_type}' as _show_i,g.order_id,g.archives_sn,g.status,count(g.id) as ok_num,g.car_id,g.status{$give_status}_time,g.address_time,g.address_date,g.address_sn,g.address_status")
            ->where($map)
            ->group("g.order_id")
            ->order('g.address_time desc')
            ->paginate()
            ->each(function ($v){

                //总数量
                $v['number'] = Db::name('mill_order_archives')
                    ->alias('a')
                    ->where(['a.order_id'=>$v['order_id']])
                    ->sum('a.number');
                //未扫
                $v['no_num'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->where(['g.order_id'=>$v['order_id']])
                    ->where("g.status < {$v['status']}")
                    ->count();

                //跳转
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}&_o=g.archives_sn=like";
                $v['ok_num_str'] = '<a href="'.url('deliverGiveShow'.$v['_show_i'],['address_sn'=>$v['address_sn']]).$url_parm.'">'.$v['ok_num'].'</a>';
                $v['no_num_str'] = '<a href="'.url('deliverGiveShow'.$v['_show_i'],['address_sn'=>$v['address_sn'],'order_ids'=>$v['order_id'],'not_address'=>1]).$url_parm.'">'.$v['no_num'].'</a>';

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        $title = "{$address_sn} 发货单明细";
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号'],
                ['engineering', '工程'],
                ['number', '总数量'],
                ['ok_num_str', '已发货'],
                ['no_num_str', '未发货'],
            ])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    public function deliverOrder2(){
        return $this->deliverOrder(2);
    }
    /**
     * 产品明细发货进度
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function deliverGiveShow($show_type='')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //发货状态
        $give_status = GiveModel::$role[8]['status'][0];
        $not_address = input('not_address');//0:已发货 1:未发货
        $order_ids = input('order_ids');//工程ID集合
        $address_sn = input('address_sn');
        $archives_sn = input('archives_sn');
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['g.quality_status','>=','-1'];

        if(!empty($map)){
            foreach ($map as $m){
                if($m[0] == 'g.archives_sn')$archives_sn = trim($m[2],'%');
            }
        }

        if($not_address == 1 && $order_ids){
            $map[] = ['g.order_id','in',$order_ids];
            $map[] = ['g.status','<',$give_status];
        }
        elseif($not_address == 1)$map[] = ['g.status','<',$give_status];
        else $map[] = ['g.address_sn','=',$address_sn];
        $map = array_merge($map);

        $table_fields = ArchivesModel::$fields4;

        unset($table_fields['status']);

        $columns = [];
        $fields = '';
        foreach ($table_fields as $k=>$v){
            if($k == 'number')$fields .= ",COUNT(g.id) as number";
            elseif ($k == 'one_area')$fields .= ",FORMAT(a.one_area,4) as one_area";
            elseif ($k == 'row_area')$fields .= ",(COUNT(g.id)*FORMAT(a.one_area,4)) as row_area";
            elseif ($k == 'batch')$fields .= ",o.{$k}";
            elseif ($k == 'pack')$fields .= ",'' AS pack";
            elseif ($k == 'make_model')$fields .= ",'' AS make_model";
            elseif ($k == 'order_sn_off')$fields .= ",o.{$k}";
            elseif ($k == 'create_time')$fields .= ",FROM_UNIXTIME(o.archives_bill_time,'%Y-%m-%d') as create_time";
            elseif (strpos($k,'konghang') !== false)$fields .= ",'' as {$k}";
            else $fields .= ",a.{$k}";

            $columns[] = [$k, $v];
        }
        $fields = trim($fields,',');

        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("g.*,o.batch,o.order_sn_off as o_batch,a.model,a.model_sn,a.thickness,a.one_area,a.color,a.sort as a_sort,o.engineering")
            //->field($fields)
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->order('g.id')
            //->group('a.id')
            //->orderRaw("a.order_id asc,CONVERT (REPLACE(a.sort,'#','999999'),signed) ASC")
            ->select();

        //统计
        $data_stat = Db::name('mill_order')
            ->alias('o')
            ->field('sum(g.number) as number_sum,sum(a.one_area) as area_sum')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->leftJoin('mill_order_archives_give g','a.id=g.archives_id')
            ->where($map)
            ->find();

        //获取该发货单号所有的工程ID
        $order_ids = Db::name('mill_order_archives_give')->alias('g')->where($map)->column('distinct(order_id)','distinct(order_id)');
        $order_ids = implode(',',$order_ids);

        // 使用ZBuilder快速创建数据表格
        $url_parm = !empty($_SERVER['QUERY_STRING'])?"?{$_SERVER['QUERY_STRING']}":'';
        //已发链接
        $url = url('deliverGiveShow'.$show_type,['address_sn'=>$address_sn]).$url_parm;
        //未发链接
        //$url2 = url('deliverGiveShow'.$show_type,['address_sn'=>$address_sn,'not_address'=>1]).$url_parm;
        $url2 = url('deliverGiveShow'.$show_type,['order_ids'=>$order_ids,'address_sn'=>$address_sn,'not_address'=>1]).$url_parm;
        if($not_address == 1){
            $title = '未';
            $topButton = ['title'=>'已发货明细','href'=>$url];
            $print_url = $url2;
            $pl_button = ['title'=>'批量补货','href'=>url('ableGive',['address_sn'=>$address_sn,'archives_sn'=>$archives_sn])];
        }
        else{
            $title = '已';
            $topButton = ['title'=>'未发货明细','href'=>$url2];
            $print_url = $url;
            $pl_button = ['title'=>'批量卸货','href'=>url('ableGive',['address_sn'=>$address_sn,'archives_sn'=>$archives_sn,'type'=>1])];
        }
        $print_url = str_replace("delivergiveshow{$show_type}","delivergiveshowprint",$print_url);
        $print_title = "{$title}发货明细";
        $title .= '发货明细（总数量'.$data_stat['number_sum'].'/总面积'.$data_stat['area_sum'].'M²）';

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$print_title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'g.archives_sn', '档案编号', 'like'],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['text:2', 'give_sn', '条码编号', 'like'],
            ])
            ->hideColumn("status{$give_status}_time")
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案编号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['model_sn', '铝板编号'],
                ['color', '颜色'],
                ['a_sort','序号','callback',function($value, $data){
                    $value = "{$value}-{$data['counter']}";
                    return $value;
                },'__data__'],
                ['give_sn', '产品条形码编号'],
                ['model', '铝板版型'],
                ['one_area', '面积M²'],
                ['number', '数量'],
                ["status{$give_status}_time",'扫码时间','callback',function($value, $data){
                    $str = '';
                    $status = abs($data['status']);
                    if(!empty($data["status{$status}_time"]))$str = date('Y-m-d H:i:s',$data["status{$status}_time"]);

                    return $str;
                },'__data__'],
                ['status','状态','callback',function($value, $data){
                    $str = '';

                    $str .= '<span class="label label-primary">'.GiveModel::$give_status[$value];
                    if($data['quality_status']<0)$str .= GiveModel::$quality_status[$data['quality_status']];
                    $str .= '</span>';
                    return $str;
                },'__data__'],
            ])
            //->addColumns($columns)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('deliverGiveShow',['title' => $topButton['title'],'href' => $topButton['href']])
            ->addTopButton('ableGive',['title' => '补货','href' => url('ableGive',['address_sn'=>$address_sn]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '45%'], 'title' => ['补货', 'font-size:24px;text-align: center;']])
            ->addTopButton('ableGive2',['title' => '卸货','href' => url('ableGive',['address_sn'=>$address_sn,'type'=>1]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '45%'], 'title' => ['卸货', 'font-size:24px;text-align: center;']])
            ->addTopButton('ableGiveBatch',['title' => $pl_button['title'],'href' => $pl_button['href'],'icon'=>'','class'=>'btn btn-primary ajax-post confirm','target-form'=>'ids'])
            //->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'])
            ->addTopButton('ablequality',['title' => '导出列表','href'=>$print_url,'icon'=>'','class'=>'btn btn-success','target'=>'_blank'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'archvies_sn'  => 200,
                'thickness'  => 50,
                'number'  => 40,
                'one_area'  => 80,
                'extra'  => 35,
                'konghang'  => 0,
                'long'  => 60,
                'high'  => 60,
                'sort'  => 60,
                //'give_sn'  => 110,
                //'status'  => 60,
                //'batch'  => 60,
                //'engineering'  => 150,
            ])
            ->noPages()
            ->fetch(); // 渲染模板
    }
    public function deliverGiveShow2(){
        return $this->deliverGiveShow(2);
    }
    public function deliverGiveShow3(){
        return $this->deliverGiveShow(3);
    }
    /**
     * 打印产品明细发货进度
     * @return mixed
     */
    public function deliverGiveShowPrint()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $not_address = input('not_address');//0:已发货 1:未发货 2:流水线明细
        $order_ids = input('order_ids');//工程ID集合
        $address_sn = input('address_sn');
        $archives_status = input('archives_status');
        $read_type = input('read_type');
        //显示单价 0:不显示 1:显示
        $is_price = input('is_price');
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['g.quality_status','>=','-1'];

        $map2 = [];
        $map3 = '';
        $archives_status2 = '';
        if(!empty($map)){
            foreach ($map as $m_v_i=>$m_v){
                if($m_v[0] == 'g.status'){
                    $archives_status = $m_v[2];
                    if(count(explode(',',$archives_status)) > 1){
                        $archives_status = explode(',',$archives_status)[0];
                        $archives_status2 = $archives_status;
                    }
                    unset($map[$m_v_i]);
                }
                elseif($m_v[0] == 'status_flow'){
                    $m_v[2] = trim($m_v[2],'%');
                    $m_v[2] = "%\\_{$archives_status}|".trim($m_v[2],'%')."\\_%";
                    $map[$m_v_i] = $m_v;
                }
                elseif ($m_v[0] == 'times'){
                    $m_v[2][0] = strtotime($m_v[2][0]);
                    $m_v[2][1] = strtotime($m_v[2][1]);
                    if($archives_status > 0){
                        if($read_type>0)$map3 .= "((g.status{$archives_status}_time between {$m_v[2][0]} and {$m_v[2][1]}))";
                        else $map3 .= "((g.quality_time between {$m_v[2][0]} and {$m_v[2][1]}) or (g.status{$archives_status}_time between {$m_v[2][0]} and {$m_v[2][1]}))";
                    }

                    unset($map[$m_v_i]);
                }

            }
        }
        $map = array_merge($map);

        if($not_address == 1){
            if($order_ids)$map[] = ['g.order_id','in',$order_ids];
            $map[] = ['g.status','<',GiveModel::$role[8]['status'][0]];
        }
        elseif($not_address == 2){

            //生产状态：0待生产，1开料，2钣金，3喷涂喷涂，4发货
            if($archives_status == 0){
                $map2[] = ['g.status','=',0];
                $order = "id DESC";
            }
            else{
                if($read_type == 2)$map2[] = ['g.status','between',[0,($archives_status-1)]];
                elseif($read_type == 3)$map2[] = ['g.status','in',[$archives_status2]];
                else $map2[] = ['g.status_flow','like',"%\\_{$archives_status}|%"];

                $order = "(CASE WHEN g.quality_status<0 THEN g.quality_time ELSE g.status{$archives_status}_time END) DESC";
            }
        }
        else $map[] = ['g.address_sn','=',$address_sn];

        $table_fields = ArchivesModel::$fields4;
        //显示单价 0:不显示 1:显示
        if(empty($is_price)){
            unset($table_fields['price']);
            unset($table_fields['price_sum']);
        }

        unset($table_fields['status']);

        $columns = [];
        $fields = '';
        foreach ($table_fields as $k=>$v){
            if($k == 'number')$fields .= ",COUNT(g.id) as number";
            elseif ($k == 'archives_id')$fields .= ",g.{$k}";
            elseif ($k == 'one_area')$fields .= ",FORMAT(a.one_area,4) as one_area";
            elseif ($k == 'row_area')$fields .= ",(COUNT(g.id)*FORMAT(a.one_area,4)) as row_area";
            elseif ($k == 'batch')$fields .= ",o.{$k}";
            elseif ($k == 'pack')$fields .= ",'' AS pack";
            elseif ($k == 'make_model')$fields .= ",'' AS make_model";
            elseif ($k == 'order_sn_off')$fields .= ",o.{$k}";
            elseif ($k == 'create_time')$fields .= ",FROM_UNIXTIME(o.archives_bill_time,'%Y-%m-%d') as create_time";
            elseif (strpos($k,'konghang') !== false)$fields .= ",'' as {$k}";
            else $fields .= ",a.{$k}";

            $columns[] = [$k, $v];
        }
        $fields = trim($fields,',');

        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            //->field("g.*,o.order_sn_off as o_batch,a.model,a.model_sn,a.thickness,a.one_area,a.color,a.sort as a_sort,o.engineering")
            ->field($fields)
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->where($map2)
            ->where($map3)
            ->group('a.id')
            ->orderRaw("a.order_id asc,CONVERT (REPLACE(a.sort,'#','999999'),signed) ASC")
            ->select();
        //echo Db::name('mill_order')->getLastSql();exit;

        // 使用ZBuilder快速创建数据表格
        if($not_address == 2){
            if($read_type == 2)$title = '未完成'.GiveModel::$give_status[$archives_status];
            elseif($read_type == 3)$title = '仓库';
            elseif($archives_status)$title = GiveModel::$give_status[$archives_status];
            else {
                $title = GiveModel::$give_status[$archives_status];
            }

            $print_title = $title;
        }
        elseif($not_address == 1)$print_title = '未发货明细';
        else $print_title = '已发货明细';

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$print_title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                    
                    
                    $("[data-action=\'fullscreen_toggle\']").click();
                    $(".quality-print").click();
                })
            </script>';

        return ZBuilder::make('table')
            ->setPageTitle($print_title) // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox()
            ->addColumns($columns)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'archvies_sn'  => 200,
                'thickness'  => 50,
                'number'  => 40,
                'one_area'  => 80,
                'extra'  => 35,
                'konghang'  => 0,
                'long'  => 60,
                'high'  => 60,
                'sort'  => 60,
                //'give_sn'  => 110,
                //'status'  => 60,
                //'batch'  => 60,
                //'engineering'  => 150,
            ])
            ->noPages()
            ->fetch(); // 渲染模板
    }
    /**
     * 发货仓库
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function warehouse()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        if(!empty($map)){
            foreach ($map as $m_v_i=>$m_v){
                if($m_v[0] == 'o.archives_sn'){
                    $archives_sn = explode(',',trim($m_v[2],'%'));
                    if(count($archives_sn) > 1){
                        foreach ($archives_sn as $k=>$v){
                            if($k > 0)$map2 .= " or ";
                            $map2 .= " o.archives_sn like '%{$v}%' ";
                        }
                        unset($map[$m_v_i]);
                    }
                }

            }
        }

        if(empty($map2))$map2 = '1';
        $map[] = ['o.give_status','>',2];
        $map = array_merge($map);
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*')
            //->leftJoin('mill_order_archives a','a.order_id=o.id and (a.status<5)')//查找还处于发货以下的产品
            ->leftJoin('mill_order_archives aa','aa.order_id=o.id and (aa.status<6)')//查找还处于发货完的产品
            ->where($map)
            ->whereRaw($map2)
            //->where('a.id IS NULL AND aa.id IS NOT NULL')
            ->where('aa.id IS NOT NULL')
            ->group('o.id')
            ->order('o.id asc')
            ->paginate()
            ->each(function ($v){
                $archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                $v = array_merge($v,$archvices);

                //库存量
                $v['ware_sum'] = $v['status3']-$v['status5'];
                $v['area_ware_sum'] = $v['status3_area_sum']-$v['area_ok_sum'];

                //跳转
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}&_o=g.archives_sn=like";
                $v['status3'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>3,'read_type'=>'1')).$url_parm.'">'.$v['status3'].'</a>';
                $v['status5'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>5,'read_type'=>'1')).$url_parm.'">'.$v['status5'].'</a>';
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}|g.status=3,4&_o=g.archives_sn=like|g.status=in";
                $v['ware_sum'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>3,'read_type'=>'3')).$url_parm.'">'.$v['ware_sum'].'</a>';

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("仓库（工程数量".$data_list->total()."）") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程', 'like'],
            ])
            ->addColumns([ // 批量添加列
                //['id', '序号'],
                ['archives_sn', '档案号'],
                ['engineering', '工程'],
                ['batch', '批次'],
                ['number_sum', '总数量'],
                //['area_sum', '总面积'],
                ['status3', '喷涂已完成数量'],
                ['status3_area_sum', '喷涂已完成面积'],
                ['status5', '已发货数量'],
                ['area_ok_sum', '已发货面积'],
                ['ware_sum', '库存量'],
                ['area_ware_sum', '库存量面积'],
                //['right_button', '操作', 'btn']
            ])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 确认装车
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function deliverSub()
    {
        //发货单号
        $address_sn = input('address_sn');
        if(empty($address_sn))$this->error("请选择发货单号");
        //同产品的信息
        $address_give = Db::name('mill_order_archives_give')
            ->where(['address_sn'=>$address_sn])
            ->find();
        //未装车
        $address_give0 = Db::name('mill_order_archives_give')
            ->where(['address_sn'=>$address_sn,'address_status'=>0])
            ->find();
        if(empty($address_give))$this->error("发货单号[{$address_sn}]不存在");
        if(empty($address_give0))$this->error("发货单号[{$address_sn}]已装车完成");

        //定时任务，超过24小时未确认发货，则自动发货
        GiveModel::taskSubGiveAddress($address_give['address_sn'],time());

        //$this->success('操作成功','','_parent_reload');
        $this->success('操作成功');
    }
    /**
     * 合并发货单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function deliverMerge()
    {
        //发货单号
        $address_sn = input('address_sn');
        if ($this->request->isPost()){

            //需要合并的发货单号
            $merge_address_sn = input('merge_address_sn');
            //同产品的信息
            $address_give = Db::name('mill_order_archives_give')
                ->where(['address_sn'=>$address_sn])
                ->find();
            $merge_address_give = Db::name('mill_order_archives_give')
                ->where(['address_sn'=>$merge_address_sn])
                ->find();
            if(empty($address_give))$this->error("发货单号[{$address_sn}]不存在");
            if(empty($merge_address_give))$this->error("发货单号[{$merge_address_sn}]不存在");
            if($address_give['address_status'] == 0)$this->error("发货单号[{$address_sn}]还在装车中");
            if($merge_address_give['address_status'] == 0)$this->error("发货单号[{$merge_address_sn}]还在装车中");
            if($address_give['order_pid'] != $merge_address_give['order_pid'])$this->error("两个发货单号不是同一批工程");
            if($address_give['car_id'] != $merge_address_give['car_id'])$this->error("两个发货单号不是同一批车辆");

            $update = [
                'address_sn'        =>  $address_give['address_sn'],
                'address_status'    =>  $address_give['address_status'],
            ];
            if(!(Db::name('mill_order_archives_give')->where(['address_sn'=>$merge_address_sn])->update($update))){
                $this->error('操作失败');
            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('合并发货单') // 页面标题
            ->addStatic('address_sn', '当前发货单号', '', $address_sn,$address_sn)
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'merge_address_sn','需要合并的发货单号', $address_sn],
            ])
            ->layout(['merge_address_sn'=>12])
            ->fetch();
    }
    /**
     * 补货OR卸货
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function ableGive(){

        //获取发货部的产品状态
        $role = GiveModel::$role[8];
        $role_status = $role['status'][0];
        //0:补货 1:卸货
        $type = intval(input('type'));
        //发货单号
        $address_sn = input('address_sn');
        if ($this->request->isPost()){

            $archives_sn = input('archives_sn');
            //同产品的信息
            $address_where = ['address_sn'=>$address_sn];
            if($archives_sn)$address_where['archives_sn'] = $archives_sn;
            $address_give = Db::name('mill_order_archives_give')
                ->where($address_where)
                ->order('address_time desc')
                ->find();
            $uid = GiveModel::giveStatusOrUid($address_give['status_flow'],null,$role_status);
            $user = Db::name('admin_user')->where(['id'=>$uid])->find();

            //勾选时的批量处理，即产品ID集合，数组格式
            $ids = input('ids');

            $give_search_post = input('give_search');
            $give_search_post = str_replace("，",",",$give_search_post);
            $give_search_arr = explode(',',$give_search_post);

            if(!empty($ids))$give_search_arr = $ids;

            foreach ($give_search_arr as $v){
                //如果产品ID集合存在，则直接调用ID
                if(!empty($ids)){
                    $where = [
                        ['g.id','=',$v]
                    ];
                }
                else{
                    //序列号仅为数字时，则更新该序列号所有的产品
                    //如果格式为2-10，则仅更新该序列号的指定产品
                    $give_search = explode('-',$v);

                    $where = [
                        ['a.sort','=',$give_search[0]],
                        ['g.archives_sn','=',$address_give['archives_sn']],
                    ];
                    if(!empty($give_search[1]))$where[] = ['g.counter','=',$give_search[1]];
                }

                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($where)
                    ->find();

                //统计是否全部发货完成，或未发货完成
                if(empty($type))$where[] = ['g.status','=',$role_status];
                else $where[] = ['g.status','<>',$role_status];
                $count = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($where)
                    ->count();

                if(empty($give))$this->error("该产品不存在[{$v}]");
                if(empty($type) && $count)$this->error("该产品已发货[{$v}]");
                elseif($type == 1 && $count)$this->error("该产品未发货[{$v}]");

            }


            foreach ($give_search_arr as $v){
                //如果产品ID集合存在，则直接调用ID
                if(!empty($ids)){
                    $where = [
                        ['g.id','=',$v]
                    ];
                }
                else{
                    //序列号仅为数字时，则更新该序列号所有的产品
                    //如果格式为2-10，则仅更新该序列号的指定产品
                    $give_search = explode('-',$v);

                    $where = [
                        ['a.sort','=',$give_search[0]],
                        ['g.archives_sn','=',$address_give['archives_sn']],
                    ];
                    if(!empty($give_search[1]))$where[] = ['g.counter','=',$give_search[1]];
                }

                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*,o.is_process')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->where($where)
                    ->group('g.id')
                    ->select();

                foreach ($give as $gv){

                    //补货
                    if(empty($type)){
                        $status = abs($gv['status']);
                        $status_flow = $gv['status_flow'];

                        //同步同产品的发货信息
                        $update = [
                            'address_sn'        =>  $address_give['address_sn'],
                            'address_date'      =>  $address_give['address_date'],
                            'address_time'      =>  $address_give['address_time'],
                            'address_status'    =>  $address_give['address_status'],
                            'car_id'            =>  $address_give['car_id'],
                        ];
                        //补上各流水线状态，默认当前操作部门用户

                        //满足发货部补扫情况，自动补满之前所有状态
                        $sup = GiveModel::$sup;
                        $sup_status = $sup[$user['group']];//需要补充到的状态
                        $status_flow_update = GiveModel::giveToStatus4($user,$status_flow,$status,$sup_status,$gv);
                        $user['mill_id'] = 0;
                        $status_flow_update2 = GiveModel::giveToStatus4($user,$status_flow_update['status_flow'],$status_flow_update['status'],$role_status,$gv);
                        $status_flow_update = array_merge($status_flow_update,$status_flow_update2);

                        $update = array_merge($update,$status_flow_update);
                    }
                    //卸货
                    elseif ($type == 1){

                        $status = $role_status;
                        foreach ($role['status'] as $v){
                            if($v != $role_status && isset(GiveModel::$give_status_search[$v]) && !GiveModel::roleMillBool($user,$v,$gv['is_process'])){
                                $status = $v;
                                break;
                            }
                        }

                        $status_flow = explode(",_{$role_status}|",$gv['status_flow']);
                        $status_flow = $status_flow[0];

                        //同步同产品的发货信息
                        $update = [
                            'status'            =>  $status,
                            'status5_time'      =>  '',
                            'status_flow'       =>  $status_flow,
                            'address_sn'        =>  '',
                            'address_date'      =>  '',
                            'address_time'      =>  '',
                            'address_status'    =>  0,
                            'car_id'            =>  '',
                        ];
                    }

                    Db::name('mill_order_archives_give')->where(['id'=>$gv['id']])->update($update);
                    ArchivesModel::checkStatus($gv['archives_id'],$update['status']);

                }



            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        //根据发货单号获取批次
        /*$batch = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where(['g.address_sn'=>$address_sn])->group('g.archives_sn')->column("concat(o.order_sn,'第',o.batch,'批') as str",'g.archives_sn');*/
        $batch = Db::name('mill_order_archives_give')->where(['address_sn'=>$address_sn])->group('archives_sn')->column('archives_sn as archives_sns','archives_sn');
        return ZBuilder::make('form')
            ->setPageTitle('补货') // 页面标题
            ->addStatic('address_sn', '发货单号', '', $address_sn,$address_sn)
            ->addHidden('type',$type)
            ->addFormItems([ // 批量添加表单项
                //['text:||||must', 'address_sn','发货单号', $address_sn],
                ['select:||||must', 'archives_sn', '档案编号','',$batch,key($batch)],
                ['text:||||must', 'give_search', '产品序列号'],
            ])
            ->submitConfirm()
            ->layout(['address_sn'=>12,'archives_sn'=>12,'give_search'=>12])
            ->fetch();

    }
}
